commit 1c4fc7e75545b926799058ea3811a31424a7ac2a Author: Noah Metz Date: Sun Dec 1 18:26:31 2024 -0700 Day 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5b4bf54 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +*.in +*.out +compile_commands.json +.cache/ + +day_* +!day_*.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..daf3902 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +CC ?= clang +CFLAGS = -O0 -g -Wall -Wextra + +%.o: %.c + $(CC) $(CFLAGS) -c -o $@ $< + +day_1: day_1.o + $(CC) -o $@ $^ + ./day_1 day_1.in diff --git a/day_1.c b/day_1.c new file mode 100644 index 0000000..51a81c8 --- /dev/null +++ b/day_1.c @@ -0,0 +1,76 @@ +#include "stdio.h" +#include "stdlib.h" +#include "string.h" + +int compare(const void* a, const void* b) { + return (*(int*)a - *(int*)b); +} + +int main(int argc, char* argv[]) { + int size = 0; + int lines = 0; + int sum = 0; + int* list1 = NULL; + int* list2 = NULL; + + if(argc < 2) { + fprintf(stderr, "Filename required\n"); + return 1; + } + + FILE* file = fopen(argv[1], "r"); + if(file == NULL) { + fprintf(stderr, "Could not open %s\n", argv[1]); + return 2; + } + + char* line = NULL; + size_t line_size = 0; + while(getline(&line, &line_size, file) > 0) { + lines += 1; + } + + rewind(file); + list1 = malloc(sizeof(int)*lines); + list2 = malloc(sizeof(int)*lines); + + for(int i = 0; i < lines; i++) { + char* line_save = NULL; + getline(&line, &line_size, file); + char* num1 = strtok_r(line, " ", &line_save); + char* num2 = strtok_r(NULL, " ", &line_save); + if(num1 == NULL || num2 == NULL) continue; + + list1[i] = atoi(num1); + list2[i] = atoi(num2); + size += 1; + } + free(line); + + qsort(list1, size, sizeof(int), compare); + qsort(list2, size, sizeof(int), compare); + + for(int i = 0; i < size; i++) { + sum += abs(list1[i] - list2[i]); + } + + fprintf(stdout, "Sum: %d\n", sum); + + int similarity = 0; + int* counts = malloc(sizeof(int)*size); + memset(counts, 0, sizeof(int)*size); + + for(int i = 0; i < size; i++) { + for(int j = 0; j < size; j++) { + if(list1[i] == list2[j]) counts[i] += 1; + } + } + + for(int i = 0; i < size; i++){ + similarity += list1[i] * counts[i]; + } + + fprintf(stdout, "Similarity: %d\n", similarity); + + return 0; +}