Use a real hashing function.

This commit is contained in:
Glenn Y. Rolland 2016-05-20 00:14:39 +02:00
parent c9c662dd00
commit 120db2838c

View file

@ -15,7 +15,13 @@ typedef struct {
} HASHTABLE; } HASHTABLE;
int hash_of_key(HASHTABLE* hashtable, char * key) { int hash_of_key(HASHTABLE* hashtable, char * key) {
return 0; int val=0;
int idx=0;
while (key[idx] != '\0') {
val ^= key[idx];
idx++;
}
return (val % hashtable->capacity);
} }
HASHTABLE* hashtable_create(int capacity) { HASHTABLE* hashtable_create(int capacity) {
@ -88,7 +94,7 @@ int hashtable_set(HASHTABLE* hashtable, char* key, void * value) {
(void*)cell->value, (void*)cell->value,
(void*)cell->next); (void*)cell->next);
} }
printf("hashtable_set -- done\n"); printf("hashtable_set(...) -- done\n");
return 0; return 0;
} }
@ -98,6 +104,7 @@ void * hashtable_get(HASHTABLE* hashtable, char* key) {
HASHCELL* cell; HASHCELL* cell;
printf("hashtable_get(%p, %p) -- \n", hashtable, key); printf("hashtable_get(%p, %p) -- \n", hashtable, key);
idx = hash_of_key(hashtable, key); idx = hash_of_key(hashtable, key);
printf("hashtable_get(...) -- index [%d/%d]\n", idx, hashtable->capacity);
cell = hashtable->data[idx]; cell = hashtable->data[idx];
while(cell) { while(cell) {
printf("hashtable_get(...) -- cell@%p{key=%s, value=%p, next=%p}\n", printf("hashtable_get(...) -- cell@%p{key=%s, value=%p, next=%p}\n",
@ -134,6 +141,7 @@ int main(int argc, char** argv) {
printf("h['charlie'] <- %d\n", z); printf("h['charlie'] <- %d\n", z);
hashtable_set(hashtable, "alice", &y); hashtable_set(hashtable, "alice", &y);
printf("h['alice'] <- %d\n", y); printf("h['alice'] <- %d\n", y);
value = hashtable_get(hashtable, "alice"); value = hashtable_get(hashtable, "alice");
printf("h['alice'] ? %d\n", *value); printf("h['alice'] ? %d\n", *value);
value = hashtable_get(hashtable, "bob"); value = hashtable_get(hashtable, "bob");