From 94f7a90a82a36c43cec6290b90553b3d9a850eb1 Mon Sep 17 00:00:00 2001 From: Parker Macdonald Date: Sat, 7 Dec 2024 17:19:18 -0700 Subject: [PATCH] day 1 part 2 --- day 1/2.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 day 1/2.c diff --git a/day 1/2.c b/day 1/2.c new file mode 100644 index 0000000..c97ba0f --- /dev/null +++ b/day 1/2.c @@ -0,0 +1,87 @@ +#include +#include + +unsigned int hash_int(unsigned int key) { + /* Robert Jenkins' 32 bit Mix Function */ + key += (key << 12); + key ^= (key >> 22); + key += (key << 4); + key ^= (key >> 9); + key += (key << 10); + key ^= (key >> 2); + key += (key << 7); + key ^= (key >> 12); + + /* Knuth's Multiplicative Method */ + key = (key >> 3) * 2654435761; + + return key; +} + +#define TABLE_SIZE 16384 +#define BUFFER_SIZE 1024 + +int main(void) { + FILE *fp = fopen("input", "r"); + + size_t lineCount = 0; + + char buffer[BUFFER_SIZE] = {0}; + + // get number of lines + size_t read = 0; + + while ((read = fread(&buffer, sizeof(char), BUFFER_SIZE, fp))) { + for (size_t i = 0; i < read; i++) { + if (buffer[i] == '\n') { + lineCount++; + } + } + } + + rewind(fp); + + // get data from file + unsigned int *left = malloc((lineCount * 2 + 1) * sizeof(int)); + // haha pointer arithmetic go brrr + unsigned int *right = left + lineCount; + + for (size_t i = 0; i < lineCount; i++) { + unsigned int leftNum, rightNum; + int numsGot = fscanf(fp, "%u %u\n", &leftNum, &rightNum); + + if (numsGot == 2) { + left[i] = leftNum; + right[i] = rightNum; + } + } + + unsigned int hash_map[TABLE_SIZE] = {0}; + + unsigned sum = 0; + for (size_t i = 0; i < lineCount; i++) { + const unsigned int key = hash_int(left[i]) % TABLE_SIZE; + + if (hash_map[key] == 0) { + unsigned int similarity_score = 0; + for (size_t j = 0; j < lineCount; j++) { + if (left[i] == right[j]) { + similarity_score++; + } + } + + similarity_score *= left[i]; + + hash_map[key] = similarity_score; + } + + sum += hash_map[key]; + } + + printf("%d\n", sum); + + free(left); + fclose(fp); + + return 0; +} \ No newline at end of file