diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/02/04/hash.c | 26 | ||||
| -rw-r--r-- | src/02/04/hash.h | 9 | ||||
| -rw-r--r-- | src/02/04/hash_test.c | 17 |
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; } |
