From ff6613d40afa4eecf8c1ec49ae75ee38daf44e03 Mon Sep 17 00:00:00 2001 From: mo khan Date: Mon, 3 Aug 2020 14:27:51 -0600 Subject: Store Tuples in the hash --- src/02/04/hash.c | 61 ++++++++++++++++++++++++-------------------------------- 1 file changed, 26 insertions(+), 35 deletions(-) (limited to 'src/02/04/hash.c') diff --git a/src/02/04/hash.c b/src/02/04/hash.c index 831c3fd..e66092a 100644 --- a/src/02/04/hash.c +++ b/src/02/04/hash.c @@ -1,53 +1,44 @@ #include "hash.h" +#include "tuple.h" #include #include #include -static int to_hash(int key) +Hash *hash_init(int size) { - return key % 13; + Hash *hash = malloc(sizeof(Hash)); + hash->size = size; + hash->buckets = calloc(size, sizeof(Node)); + return hash; } -Hash *hash_init(int buckets) +int hash_index(Hash *hash, int key) { - Hash *hash = malloc(sizeof(Hash)); - /*hash->head = node_initialize(NULL);*/ - /*Node *current = hash->head;*/ - - /*for (int i = 1; i < buckets; i++) {*/ - /*current->next = node_initialize(NULL);*/ - /*current = current->next;*/ - /*}*/ - return hash; + return key % hash->size; } void *hash_get(Hash *hash, int key) { - /*int bucket = to_hash(key);*/ - /*Node *node = node_at(hash->head, bucket);*/ - /*node_inspect(hash->head);*/ - /*printf(" ");*/ - /*node_inspect(node);*/ - - /*if (!node->value) {*/ - /*return NULL;*/ - /*}*/ - - /*Tuple *t = (Tuple *)node->value;*/ - /*if (t->key == key) {*/ - /*return node->value;*/ - /*}*/ + int bucket = hash_index(hash, key); + Node *list = hash->buckets + bucket; + if (list && list->data) + return ((Tuple *)list->data)->value; + else + return NULL; +} - /*return node->value;*/ - return NULL; +void hash_set(Hash *hash, int key, void *value) +{ + int bucket = hash_index(hash, key); + Node *node = list_initialize(tuple_initialize(key, value)); + hash->buckets[bucket] = *node; + hash_inspect(hash); } -void hash_set(Hash *hash, int key, void **value) +void hash_inspect(Hash *hash) { - int bucket = to_hash(key); - /*Node *node = node_at(hash->head, bucket);*/ - /*Tuple *tuple = malloc(sizeof(Tuple));*/ - /*tuple->key = key;*/ - /*tuple->value = value;*/ - /*list_add(node, tuple);*/ + for (int i = 0; i < hash->size; i++) { + printf("%2d: ", i); + list_inspect(hash->buckets + i); + } } -- cgit v1.2.3