Reputation:
So I got a integer variable between 1 and 10,000
.
I'd like to convert every number to a unique!
hash value that has a fixed length and has a custom charset (includes all alphabetic lowercase and uppercase characters).
So:
n=10
could get to result="AVduujANNiO"
n=4507
could get to result="BciidEPpaEo"
I do not really know how to develop an algorithm like this so this is all I got so far. I think the algorithm should work but of course I get a integer value as hash - not a alphabetic value. No idea how to fix this and how to pad the result to give it a fixed length.
I really hope somebody is able to help me.
let value = "3325";
var getHash = function(value) {
let hash = 0;
for (let i = 0; i < value.length; i++) {
let char = value.charCodeAt(i);
hash = (hash << 6) + char + (char << 14);
hash=-hash
} return hash;
};
console.log(getHash(value))
Upvotes: 0
Views: 333
Reputation: 23955
Here's a hash function that seems to do what you are asking for :) As a bonus, it offers no collisions til 100,000.
function h(n){
let s = [
'0101000', '1011010', '0011111',
'1100001', '1100101', '1011001',
'1110011', '1010101', '1000111',
'0001100', '1001000'].map(x => parseInt(x, 2));
let m = parseInt('101', 2);
s = s.map(x => {
n ^= m;
m <<= 1;
return (x ^ n) % 52;
});
return s.map(x =>
String.fromCharCode(x > 25 ? 71 + x : 65 + x)
).join('');
}
const s = {};
for (let j=1; j <=10000; j++){
let hash = h(j);
if (s[hash])
console.log('Collision! ' + j + ' <-> ' + s[hash]);
s[hash] = j;
}
console.log('Done. No collisions below 10000.');
for (let j=1; j <11; j++)
console.log(j, h(j));
Upvotes: 2