diff --git a/c/lib/aoc.h b/c/lib/aoc.h index aac3147..1576529 100644 --- a/c/lib/aoc.h +++ b/c/lib/aoc.h @@ -2,6 +2,8 @@ #include #include +#include "hashmap.h" + #define INITIAL_BUFFER_SIZE 2 char *input_buffer; diff --git a/c/lib/hashmap.h b/c/lib/hashmap.h new file mode 100644 index 0000000..1c81d16 --- /dev/null +++ b/c/lib/hashmap.h @@ -0,0 +1,44 @@ +#define AOC_HASHMAP_RADIX 1024 + +int aoc_hash(const char *string) { + int len = strlen(string); + int hash = 1; + for (int i = 0; i < len; i++) { + hash *= 7; + hash += string[i] * 13; + hash %= AOC_HASHMAP_RADIX; + } + + return hash; +} + +typedef struct AocHashmapNode AocHashmapNode; + +typedef struct AocHashmapNode { + char *key; + long value; + AocHashmapNode *next; +} AocHashmapNode; + +typedef struct AocHashmap { + AocHashmapNode* buckets[AOC_HASHMAP_RADIX]; +} AocHashmap; + +AocHashmapNode *aoc_hashmap_get(AocHashmap *map, char *key) { + int hash = aoc_hash(key); + AocHashmapNode *node = map->buckets[hash]; + while (node != NULL && strcmp(node->key, key) != 0) node = node->next; + return node; +} + +void *aoc_hashmap_put(AocHashmap *map, char *key, long value) { + int hash = aoc_hash(key); + AocHashmapNode *node = map->buckets[hash]; + while (node != NULL) node = node->next; + map->buckets[hash] = malloc(sizeof(AocHashmapNode)); + node = map->buckets[hash]; + node->key = malloc(strlen(key) + 1); + strcpy(node->key, key); + node->value = value; + node->next = NULL; +}