I am implementing hash function in order to check the anagrams, but I am not getting desired output. Could you suggest what went wrong?
Output:
key[148]:val[joy]
key[174]:val[jam]
key[294]:val[paula]
key[13]:val[ulrich]
key[174]:val[cat]
key[174]:val[act]
key[148]:val[yoj]
key[265]:val[vij]
key[265]:val[jiv]
Here key value 174
is fine for strings act
and cat
(anagrams) but same can't be expected with jam
.
Below is the code snippet.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned long hash(char *str, size_t size) {
unsigned long hash_val = 5381;
unsigned long sum = 0;
char *val;
int i, j;
for (j = 0; j < 9; j++) {
val = malloc(strlen(str) + 1);
memset(val, '\0', strlen(str) + 1);
strcpy(val, str);
for (i = 0; val[i] != '\0'; i++) {
sum = sum + val[i];
}
return size % sum;
}
}
int main() {
int i;
char *str[9] = { "joy", "jam", "paula", "ulrich","cat", "act","yoj", "vij", "jiv" };
unsigned long key;
size_t size = 4542; // it may be anything just for test it is being used
for (i = 0; i < 9; i++) {
key = hash(str[i], size);
printf("\nkey[%ld]:val[%s]", key, str[i]);
}
return 1;
}