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.
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('');
}
const chai = require("chai");
const assert = chai.assert;
describe("Solution", () => {
describe("Alphabet", () => {
const alphabet = [...Array(26)].map((e,i) => (i+10).toString(36)); // ['a','b','c','d', ...]
it("Should return correct to first position", () => {
for (const [index, value] of Object.entries(alphabet)) {
assert.strictEqual(getOdometerChars(alphabet, parseInt(index) + 1), value);
}
});
it("Should return next positions", () => {
assert.strictEqual(getOdometerChars(alphabet, 27), 'aa');
assert.strictEqual(getOdometerChars(alphabet, 52), 'az');
assert.strictEqual(getOdometerChars(alphabet, 53), 'ba');
assert.strictEqual(getOdometerChars(alphabet, 54), 'bb');
assert.strictEqual(getOdometerChars(alphabet, 99), 'cu');
assert.strictEqual(getOdometerChars(alphabet, 425), 'pi');
assert.strictEqual(getOdometerChars(alphabet, 1000), 'all');
});
})
});