A while back I learned of these great algorithms:
function parseInt(value, code) {
let x = 0
let i = 0
while (i < value.length) {
const a = value[i]
x = x * code.length + code.indexOf(a)
i++
}
return x
}
function toString(value, code) {
const radix = code.length
let result = ''
do {
const digit = value % radix
result = code[digit] + result
value = Math.floor(value / radix)
} while (value)
return result
}
which allow you to convert toString
any (albeit 32-bit) number to a string using a custom "alphabet" or "code", and do the reverse and parse a corresponding string to int.
console.log(parseInt('dj', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
// 123
console.log(toString(123, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
// dj
console.log(parseInt('a', 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
// 0
console.log(toString(0, 'abcdefghijklmnopqrstuvwxyz0123456789+-'));
// a
How do you prove that these algorithms actually do the trick? What does the proof look like from base principles? Tangent/bonus: How would you ever go about figuring this out from scratch? To me this is pure magic and I would never have been able to figure this out "from scratch". I would like to know what I could've done to figure this out using mathematical techniques/principles.