Example 1 — Sum hash versus polynomial hash
"cat" and "act" are anagrams; the table has 11 slots.
#include <stdio.h>
static unsigned sum_hash(const char *s, unsigned m) {
unsigned h = 0;
while (*s) h += (unsigned char)*s++;
return h % m;
}
static unsigned poly_hash(const char *s, unsigned m) {
unsigned long h = 0;
while (*s) h = h * 31 + (unsigned char)*s++;
return (unsigned)(h % m);
}
int main(void) {
const char *words[] = {"cat", "act", "dog"};
for (int i = 0; i < 3; i++)
printf("%s: sum=%u poly=%u\n", words[i],
sum_hash(words[i], 11), poly_hash(words[i], 11));
return 0;
} How It Works
- "cat" and "act" have the same letters, so the sum hash gives both slot 4.
- The polynomial hash depends on position and separates them (10 and 9).
- Both reduce the hash with
% 11.
