Created
January 14, 2015 15:58
-
-
Save mtford90/1a560e7c78f5d52ebff2 to your computer and use it in GitHub Desktop.
sdgsdfgsdg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var LETTERS = 'acdegilmnoprstuw'; | |
/** | |
* The provided hash function with additional logging | |
* @param s | |
* @returns {number} | |
*/ | |
function hash(s) { | |
var h = 7; | |
for (var i = 0; i < s.length; i++) { | |
var s2 = s[i]; | |
var l = LETTERS.indexOf(s2); | |
console.log(h + ' * ' + 37 + ' + ' + l); | |
h = (h * 37 + l); | |
} | |
return h; | |
} | |
/* | |
7 * 37 + 6 | |
265 * 37 + 3 | |
9808 * 37 + 3 | |
362899 * 37 + 10 | |
13427273 * 37 + 0 | |
496809101 * 37 + 2 | |
18381936739 * 37 + 4 | |
680131659347 | |
*/ | |
console.log(hash('leepadg')); | |
/* | |
Working backwards from the above: | |
- Need to get 4 from: 680131659347 / 37 = 18381936739.10811 | |
- (680131659347 / 37 + 4) / 37 = 680131659347 + 4/37 | |
- Therefore 4/37 * 37 would get the index back | |
- There are 16 letters therefore decimal places will never be above 16/37 | |
- We can get the index by multiplying the decimal place by 37! | |
*/ | |
/** | |
* The reverse of the above hash | |
* @param n | |
* @returns {string} | |
*/ | |
function reverse(n) { | |
var str = ''; | |
while (n - 37 > 0) { | |
var f = n / 37, | |
decimalPart = f % 1, | |
idx = Math.round(37 * decimalPart), | |
char = LETTERS[idx]; | |
n = f - decimalPart; | |
str = char + str; | |
} | |
return str; | |
} | |
console.log(reverse(680131659347)); // leepadg | |
console.log(reverse(956446786872726)); // trellises |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment