s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]
Where:
"s[i]" is integer code of the ith character in string
"n" is the length of the string
"^" indicates exponentiation
This calculation should use 32-bit signed integers (overflow is okay)
String Hash Function Samples
Here is a list of strings along with the computed hash code (using the formula from the previous step).
String
Hash Code (Java)
EMPTY STRING
0
foo
101574
foofoo
-1268874688
asofiaso
-487121283
8967867
-155975625
870870707878978
1980649663
123
48690
asha@here.com
-859259272
Notes:
The Java hashCode function returns an "int" data type (four bytes). That is the reason for the negative hash codes, which are perfectly acceptable.
A JavaScript implmentation of the hashCode formula above will result in different hash codes because it uses a different number data type than Java. This difference is perfectly acceptable.
In JavaScript, we need to code a hash function for the String object type as follows.
String.prototype.hashCode = function() {
//TODO -- will not ruin your fun//implement algorithm from this page here//A number can be converted to a 32 bit signed integer via "int32 = num & num;"
}
Testing Hash Function
let log = console.log;
let s = 'foo';
log(`s: ${s} -- hashCode: ${s.hashCode()}`);
In JavaScript, we need to code a hash function for the Number object type as follows.
Number.prototype.hashCode = function() {
//This method assumes that String understands "hashCode"let n = this.valueOf(); //unwrap to prim
if (Number.isInteger(n))
return n
else
return ('' + n).hashCode();
}
Testing Hash Function
let log = console.log;
let n = 25;
log(`n: ${n} -- hashCode: ${n.hashCode()}`);
n = 25.82;
log(`n: ${n} -- hashCode: ${n.hashCode()}`);
We are given:
key = 'asha@here.com'
hashCode = -859259272
arraySize = 1000
Hash Code to Array Index
//Step 1 -- get hash code from keylet hashCode = key.hashCode();
//-859259272//Step 2 -- convert hash code to absolute value to assure non-negative indexlet index = convert hashCode to absolute value
//859259272//Step 3 -- finally use the modulus (remainder) operator is valid index for given array size
index = index % arraySize
//272//for our sample, the result is 272 (which is a valid index for an array of size 1000)