summaryrefslogtreecommitdiff
path: root/src/02
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-08-01 21:25:11 -0600
committermo khan <mo.khan@gmail.com>2020-08-01 21:25:11 -0600
commitdb7f5fa764bed00f26bd522758772b610a4f08ef (patch)
tree7840d54e29d2d14b709fac8ded648878e8bb3c21 /src/02
parentc04295209d4bebf82e8d2b9b76c978be36b8a3fa (diff)
Build a hacky hash table
Diffstat (limited to 'src/02')
-rw-r--r--src/02/04/hash.c26
-rw-r--r--src/02/04/hash.h9
-rw-r--r--src/02/04/hash_test.c17
3 files changed, 51 insertions, 1 deletions
diff --git a/src/02/04/hash.c b/src/02/04/hash.c
index c1a2bf9..9986173 100644
--- a/src/02/04/hash.c
+++ b/src/02/04/hash.c
@@ -1,7 +1,31 @@
#include "hash.h"
#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static int to_hash(int key)
+{
+ return key % 13;
+}
Hash *hash_init(int size)
{
- return NULL;
+ Hash *hash = malloc(sizeof(Hash));
+ hash->size = size;
+ return hash;
+}
+
+int hash_get(Hash *hash, int key)
+{
+ int bucket = to_hash(key);
+ Node node = hash->buckets[bucket];
+ return node.data;
+}
+
+void hash_set(Hash *hash, int key, int value)
+{
+ int bucket = to_hash(key);
+ Node node = hash->buckets[bucket];
+ node.data = value;
+ return;
}
diff --git a/src/02/04/hash.h b/src/02/04/hash.h
index 6301584..b87f06c 100644
--- a/src/02/04/hash.h
+++ b/src/02/04/hash.h
@@ -1,4 +1,13 @@
+typedef struct node {
+ struct node *next;
+ int data;
+} Node;
+
typedef struct {
+ Node buckets[13];
+ int size;
} Hash;
Hash *hash_init(int size);
+int hash_get(Hash *hash, int key);
+void hash_set(Hash *hash, int key, int value);
diff --git a/src/02/04/hash_test.c b/src/02/04/hash_test.c
index 6eeaebd..9073897 100644
--- a/src/02/04/hash_test.c
+++ b/src/02/04/hash_test.c
@@ -12,10 +12,27 @@ Ensure(HashTable, when_initializing_a_hash) {
assert_that(hash, is_not_equal_to(NULL));
}
+Ensure(HashTable, when_getting_a_value_for_a_key_that_has_not_been_inserted) {
+ Hash *hash = hash_init(13);
+
+ assert_that(hash_get(hash, 1), is_equal_to(NULL));
+}
+
+Ensure(HashTable, when_getting_a_values_for_a_key_that_has_been_inserted) {
+ int key = 7;
+ int value = 100;
+ Hash *hash = hash_init(13);
+
+ hash_set(hash, key, value);
+ assert_that(hash_get(hash, key), is_equal_to(value));
+}
+
TestSuite *hash_table_tests() {
TestSuite *suite = create_test_suite();
add_test_with_context(suite, HashTable, when_initializing_a_hash);
+ add_test_with_context(suite, HashTable, when_getting_a_value_for_a_key_that_has_not_been_inserted);
+ add_test_with_context(suite, HashTable, when_getting_a_values_for_a_key_that_has_been_inserted);
return suite;
}