I'm working on a hash function that gives a given string an "ID" by mapping that string to a key. The algorithm I need to use is described below:
Given the string
NOTE, we assign a value to each letter, for example:N = 14, O =15, T = 20, E = 5Then we multiply and add:
14 * 32^3 + 15 * 32^2 + 20 * 32^1 + 5 * 32^0By factoring this expression we get:
((14 * 32 + 15) * 32 + 20) * 32 + 5But that value might get too large so we use mod division after each set of parentheses as such:
((14 * 32 + 15)%tableSize *32 + 20)%tableSize * 32 + 5
How can I create an algorithm to accomplish this? I have tried to do it but my implementation is extremely inefficient. My professor said it shouldn't be longer than 7 lines. Can anyone offer suggestions on how to efficiently implement the above algorithm?
My algorithm in case anyone cares is:
int HashDictionary::getKey(string word) const{
int wordLength = word.length();
int* values = new int[wordLength];
for ( int i = 0; i < wordLength; i++ ) {
values[i] = int(word[i]);
}
int productSoFar = 0;
for(int i = 0; i < wordLength;i++){
productSoFar *= 32;
if(i == 0){
productSoFar = values[i] * 32;
productSoFar = productSoFar + values[i+1];
productSoFar %= tableSize;
i++;
}
else{
productSoFar += values[i];
productSoFar %= tableSize;
}
}
delete [] values;
return productSoFar;
}
i++inside theif()condition? Also, are you using C#?