summaryrefslogtreecommitdiff
path: root/src/02/04/hash.c
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-08-03 14:27:51 -0600
committermo khan <mo.khan@gmail.com>2020-08-03 14:27:51 -0600
commitff6613d40afa4eecf8c1ec49ae75ee38daf44e03 (patch)
tree25b4c715b71e67964d62efbb4ae7e1cc899f7745 /src/02/04/hash.c
parente291a2c6b57af1889010529031e07d5236fc1570 (diff)
Store Tuples in the hash
Diffstat (limited to 'src/02/04/hash.c')
-rw-r--r--src/02/04/hash.c61
1 files changed, 26 insertions, 35 deletions
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
-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);
+ }
}