Skip to content

Instantly share code, notes, and snippets.

@EleDiaz
Last active February 5, 2020 11:09
Show Gist options
  • Select an option

  • Save EleDiaz/0b1210eeebc0d67d67e41339465d1640 to your computer and use it in GitHub Desktop.

Select an option

Save EleDiaz/0b1210eeebc0d67d67e41339465d1640 to your computer and use it in GitHub Desktop.
function CreateSequence(encodeLen, alphabetLen) {
let sequence = [Math.pow(10, encodeLen)]
for (let i = 1; i <= encodeLen; i++) {
sequence.push(
sequence[i-1] +
Math.pow(10, encodeLen - i) * Math.pow(alphabetLen, i)
);
}
return sequence
}
// Value, valor a convertir
// encodeLen, tamaño de la codificación
// alphabetLen tamaño del alfabeto
// Encode(17575, 3, 26) => "ZZZ"
// Encode(3601, 3, 26) => "1AA"
// Encode(3600, 3, 26) => "0AA"
// Encode(3599, 3, 26) => "99A"
// Encode(0, 3, 26) => "000"
function Encode(value, encodeLen, alphabetLen) {
let sequence = CreateSequence(encodeLen, alphabetLen)
let ix = 0
// Se busca en la secuencia los niveles donde la base cambia y se obtiene la base
// de las letras
while (value >= sequence[ix]) ix++;
ix--;
// El caso de que no hay letras
let newValue
if (ix < 0) {
newValue = value
}
else {
newValue = value - sequence[ix]
}
console.log(newValue)
// Se obtienen las letras según la base anterior ix
let letters = []
for (let i = ix; i >= 0; i--) {
let result = Math.pow(10, encodeLen - 1 - ix) * Math.pow(alphabetLen, i)
letters.push(GetChar(newValue / result))
newValue = newValue % result;
}
return (newValue != 0 ? newValue : "0".repeat(encodeLen - 1 - ix)) + letters.join("")
}
function GetChar(value) {
return String.fromCharCode(65 + value)
}
function Decode(charExpr, alphabetLen) {
// TODO
}
// export default {CreateSequence, Encode, GetChar}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment