Ad
Algorithms
Performance

You should get all chars into a list and use it to make odometer.

When you receive a number you should return the distance in this list.

Image

The list could be any char:

list_a = ['a', 'b', 'c']
list_b = ['.', '!', '#']
list_c = ['0', '1', '2']

For example the outputs for list_a with these input will be:

| input | output |
| 0     | 'a'    |
| 1     | 'b'    |
| 2     | 'c'    |
| 3     | 'aa'   |
| 4     | 'ab'   |
| 5     | 'ac'   |
| 6     | 'ba'   |
| 7     | 'bb'   |
| 8     | 'bc'   |
| 9     | 'ca'   |
| ...   | ...    |
| 13    | 'aaa'  |
| 14    | 'aab'  |
| ...   | ...    |
| 39    | 'ccc'  |
| 40    | 'aaaa' |
| 41    | 'aaab' |
| ...   | ...    |
| 100   | 'caca' |
function getNextChar(list, odometer, n, i = 0) {
  let counter = n;
  
  while (counter - 1 >= list.length) {    
    counter -= list.length;
    getNextChar(list, odometer, 1, i + 1);
  }
  
  if (odometer[i] === null && i !== 0) {
    odometer[i] = 0;
  } else {    
    odometer[i] += counter - (i === 0 ? 1 : 0);
    
    if(odometer[i] >= list.length) {
      getNextChar(list, odometer, 1, i + 1);
      odometer[i] = 0;
    }
  }
}

function getOdometerChars(list, n) {
  let length = 1;
  
  if (n > list.length) {
    do { length += 1; } while((Math.pow(list.length, length) + list.length) < n)
  }
  
  const odometer = Array.from({ length }).fill(null);
    
  getNextChar(list, odometer, n);
    
  return odometer.reverse().map(p => list[p]).join('');
}