diff --git a/c/2024/19/linen_layout.c b/c/2024/19/linen_layout.c index 8bcbe8f..7564bcb 100644 --- a/c/2024/19/linen_layout.c +++ b/c/2024/19/linen_layout.c @@ -47,11 +47,11 @@ int main() { Towels towels; towels.towels_count = 0; towels.map = malloc(sizeof(AocHashmap)); + for (int i = 0; i < AOC_HASHMAP_RADIX; i++) { towels.map->buckets[i] = NULL; } - line = aoc_read_line(); char *token = strtok(line, ", "); while (token != NULL) { @@ -71,6 +71,7 @@ int main() { printf("Part 1: %d\n", valid_single_designs); printf("Part 2: %ld\n", valid_multi_designs); + aoc_hashmap_free(towels.map); aoc_free(); exit(0); } diff --git a/c/lib/hashmap.h b/c/lib/hashmap.h index 0bdc575..a55ce5f 100644 --- a/c/lib/hashmap.h +++ b/c/lib/hashmap.h @@ -31,14 +31,39 @@ AocHashmapNode *aoc_hashmap_get(AocHashmap *map, char *key) { return node; } -void *aoc_hashmap_put(AocHashmap *map, char *key, void *value) { +void aoc_hashmap_put(AocHashmap *map, char *key, void *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; + if (node == NULL) { + 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; + } else { + AocHashmapNode *next = node->next; + while (node->next != NULL) { + node = node->next; + } + node->next = malloc(sizeof(AocHashmapNode)); + node->next->key = malloc(strlen(key) + 1); + strcpy(node->next->key, key); + node->next->value = value; + node->next->next = NULL; + } +} + +void aoc_hashmap_free(AocHashmap *map) { + for (int i = 0; i < AOC_HASHMAP_RADIX; i++) { + AocHashmapNode *node = map->buckets[i]; + while (node != NULL) { + AocHashmapNode *next = node->next; + free(node->key); + free(node->value); + free(node); + node = next; + } + } + free(map); }