I have been working on the speller problem in pset5 for a while now, and I am not able to figure out the problem in my hash function:
unsigned int hash(const char* word)
{
int M = 1000000001;
int P = 31;
int hash_value = 0;
int p_pow = 1;
int len = strlen(word);
for (int i = 0; i < len; i++)
{
hash_value = (hash_value + (word[i] - 'a' + 1) * p_pow) % M;
p_pow = (p_pow * P) % M;
}
return hash_value;
}
Source : https://cp-algorithms.com/string/string-hashing.html
If I run my program with this hash function, following errors come on doing check50
:) dictionary.c, dictionary.h, and Makefile exist
:) speller compiles
:( handles most basic words properly
expected "MISSPELLED WOR...", not ""
:) handles min length (1-char) words
:( handles max length (45-char) words
expected "MISSPELLED WOR...", not ""
:( handles words with apostrophes properly
expected "MISSPELLED WOR...", not "MISSPELLED WOR..."
:) spell-checking is case-insensitive
:( handles substrings properly
expected "MISSPELLED WOR...", not ""
:| program is free of memory errors
can't check until a frown turns upside down
Whereas if I use any other hash function, such as:
unsigned int hash(const char* word)
{
unsigned int hash_value = 0;
for (int i = 0, n = strlen(word); i < n; i++)
{
hash_value = (hash_value << 2) ^ word[i];
}
return hash_value % N; //N is size of hashtable
}
The program compiles correctly with everything green.
Since both the hash functions should work fine, I am confused why the first one is not working properly.
Any help would be kindly appreciated.
word[i]
into an integer, i. e. try(int)word[i]
instead ofword[i]
in line 4 inside the for loop.