I was looking up different hash functions and was getting really confused following what the code was doing. I stumbled upon this hash function:
int hash(const char * str) {
int hash = 401;
int c;
while (*str != '\0') {
hash = ((hash << 4) + (int)(*str)) % MAX_TABLE;
str++;
}
return hash % MAX_TABLE;
}
At first I was unsure what was going on but someone explained to me that
- 401 is a seed value (unsure if i'll need one),
- int c is unused and probably unnecessary,
- ((hash << 4) shifts binary values 4 digits to the left (unsure why this was done),
- +(int)(*str) adds the integer value of the character at the pointer position to hash, (which I don't really understand)
- and that %MAX_TABLE returns the value from hash modulo table size to make sure you have an index value that is within the bounds of the table size.
The seed value I still do not fully understand as well as the line hash = ((hash <<4) + (int)(*str)) %MAX_TABLE. I think it is the look throwing me off (reading it like a math equation) if anyone can ellaborate I would appreciate it.
Also, would this be a good function to use if I utilize toupper/tolower? The person I reached out to said
The only drawback with this is that later on when you compare the words from the text to the dictionary, it will return more misspelled words. This is down to this part of the hash function, (int)(*str). The numeric value of 'A' is different to 'a' so if you're trying to compare Ant with ant it will come up with a different value and say that the word is misspelled so you need to add some way or lowering the case of each letter in your hash function before you add it's value to hash.