Skip to content

Instantly share code, notes, and snippets.

@jackhftang
Last active September 6, 2016 13:30
Show Gist options
  • Save jackhftang/14193b3cc8dd80ec3f48b91abbb97220 to your computer and use it in GitHub Desktop.
Save jackhftang/14193b3cc8dd80ec3f48b91abbb97220 to your computer and use it in GitHub Desktop.
permute integer range [0, 56800235583]
const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
const digitsReverse = (function(){
var arr = digits.split('');
var table = {};
for(var i=0; i<arr.length; i++) table[arr[i]] = i;
return table;
})();
const dim = 7;
const modulo = 36;
const shift = [11, 21, 21, 23, 4, 24, 1];
const forward = [
[11, 0, 7, 19, 19, 5, 23],
[31, 4, 30, 5, 18, 22, 31],
[6, 4, 13, 26, 12, 30, 32],
[11, 5, 11, 20, 25, 30, 14],
[33, 28, 2, 8, 20, 5, 18],
[17, 20, 16, 11, 21, 2, 10],
[30, 23, 27, 23, 29, 10, 14]
];
const backward = [
[7, 25, 25, 29, 27, 15, 33],
[25, 23, 18, 9, 11, 34, 20],
[14, 26, 3, 16, 20, 26, 4],
[11, 9, 31, 18, 31, 1, 10],
[22, 12, 12, 17, 20, 21, 9],
[5, 33, 17, 33, 26, 25, 9],
[22, 1, 34, 25, 24, 2, 17]
];
function encode(id) {
// O(dim)
var arr = new Array(dim);
for (let i=0; i<dim; i++){
arr[i] = id % modulo;
id = Math.floor(id/modulo);
}
// O(dim^2)
var res = shift.concat();
for(let i=0; i<dim; i++){
for(let j=0; j<dim; j++){
res[i] += forward[i][j] * arr[j];
}
}
return res.map(i => digits[i%modulo]).join('');
}
function decode(hash) {
// assert( hash.length == dim )
// O(dim)
var arr = new Array(dim);
for(let i=0; i<dim; i++){
var c = hash[i];
arr[i] = digitsReverse[c] + modulo - shift[i];
}
// O(dim^2)
var ans = 0;
var base = 1;
for(let i=0; i<dim; i++){
var t = 0;
for(let j=0; j<dim; j++){
t += backward[i][j] * arr[j];
}
ans += (t%modulo) * base;
base *= modulo;
}
return ans;
}
module.exports = {
encode: encode,
decode: decode
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment