String hash function #1

This hash function adds up the integer values of the chars in the string (then need to take the result mod the size of the table):
int hash(std::string const & key) {
int hashVal = 0, len = key.length();
for(int i=0; i<len; i++) {
hashVal += key[i]; }
return hashVal;
}

This function is simple to compute, but it often doesn’t work very well in practice:

Suppose the keys are strings of 8 ASCII capital letters and spaces

There are 27
8
possible keys; however, ASCII codes for these characters are in the range 6595, and so the sums of 8 char values will be in the range 520  760

In a large table (M>1000), only a small fraction of the slots would ever be mapped to by this hash function! For a small table (M<100), it may be okay
CONTENTS PREVIOUS NEXT