Why are we adding 'a'+1 to the string?
We are not adding, we are subtracting. Moreover, we aren't doing it to the string, we do it to one character at a time.
Here is what it does, according to the authors's intentions: given a letter from a to z, the expression produces the sequence number of that letter: 'a' produces 1, 'b' produces 2, 'c' produces 3, and so on.
Unfortunately, this implementation is broken: when the letter is in upper case, isalpha returns true, but the result of the expression does not give you the letter number. In fact, if your computer uses encoding that is consistent with ASCII codes, the result would be a negative number.
why are we doing the following: hash = ((hash << 3) + n) % SIZE
This multiplies the prior value of hash by eight (shift by three is the same as multiplying by eight), adds the number of the letter, and then limits the value by obtaining the remainder of division by SIZE.
Since the actual value of the hash code is of very little interest, as long as it is sensitive to small changes in the word, you could use this function instead:
int hash (const char* word)
{
unsigned int hash = 0;
for (int i = 0 ; word[i] != '\0' ; i++)
{
hash = 31*hash + word[i];
}
return hash % SIZE;
}
This algorithm (without the SIZE limit) is used for calculating hash codes of Strings in Java. It is very simple and very efficient.
ndoesn't end up being 0.