From db7f5fa764bed00f26bd522758772b610a4f08ef Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 1 Aug 2020 21:25:11 -0600 Subject: Build a hacky hash table --- src/02/04/hash.c | 26 +++++++++++++++++++++++++- src/02/04/hash.h | 9 +++++++++ src/02/04/hash_test.c | 17 +++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) (limited to 'src/02') 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 +#include +#include + +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; } -- cgit v1.2.3