write-a-hash-table
write-a-hash-table copied to clipboard
Hash pseudo code does not match actual code
The pseduo-code
hash = 0
string_len = length(string)
for i = 0, 1, ..., string_len:
hash += (a ** (string_len - (i+1))) * char_code(string[i])
hash = hash % num_buckets
return hash
takes the modulus of the hash value and the number of buckets once, immediately before returning it. The actual code
static int ht_hash(const char* s, const int a, const int m) {
long hash = 0;
const int len_s = strlen(s);
for (int i = 0; i < len_s; i++) {
hash += (long)pow(a, len_s - (i+1)) * s[i];
hash = hash % m;
}
return (int)hash;
}
takes the modulus of the hash value and the number of buckets for each letter in the input string.
yep, the pseudocode is a little difference with the actual code, but the results are equally :)
The results are not equal. Run this and see it outputs 21, not 5 as in the pseudo-code. Although, it's probably because of C precision vs Python precision.
#include <stdio.h>
// hash_table.c
static int ht_hash(const char* s, const int a, const int m) {
long hash = 0;
const int len_s = strlen(s);
for (int i = 0; i < len_s; i++) {
hash += (long)pow(a, len_s - (i+1)) * s[i];
hash = hash % m;
}
return (int)hash;
}
int main()
{
printf("Hello World, %d", ht_hash("cat", 163, 53));
return 0;
}