Commit db7f5fa
Changed files (3)
src
02
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;
}
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);
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;
}