From 1f6d987c5391c5d71ec58d5391c2045700d23d87 Mon Sep 17 00:00:00 2001 From: Joseph Montanaro Date: Mon, 2 Dec 2024 09:58:45 -0500 Subject: [PATCH] add 2024 day 1 --- .gitignore | 2 ++ 2024/01.c | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 2024/01.c diff --git a/.gitignore b/.gitignore index 046a5d8..90f8ec7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ */data/* */target/* **.exe + +*.out diff --git a/2024/01.c b/2024/01.c new file mode 100644 index 0000000..8ced499 --- /dev/null +++ b/2024/01.c @@ -0,0 +1,79 @@ +#include "stdio.h" +#include "stdlib.h" +#include "string.h" + + +int cmp(const void *a, const void *b) { + int *_a = (int *)a; + int *_b = (int *)b; + return *_a - *_b; +} + + +int count_occurrences(int num, int arr[], int len) { + int total = 0; + for (int i = 0; i < len; i++) { + if (arr[i] == num) { + total++; + } + } + return total; +} + + +int part1(int nums_l[], int nums_r[], int len) { + int sum = 0; + for (int i = 0; i < len; i++) { + int diff = nums_l[i] - nums_r[i]; + if (diff < 0) { + diff = diff * -1; + } + sum += diff; + } + return sum; +} + + +int part2(int nums_l[], int nums_r[], int len) { + int score = 0; + for (int i = 0; i < len; i++) { + score += nums_l[i] * count_occurrences(nums_l[i], nums_r, len); + } + return score; +} + + +int main() { + FILE *file = fopen("data/01.txt", "r"); + char *data = (char *)malloc(16384); + size_t data_len = fread(data, 1, 16384, file); + + int nums_l[1000]; + int nums_r[1000]; + + int nlines = 0; + while (1) { + char* line = strsep(&data, "\n"); + int left = strtol(line, &line, 10); + int right = strtol(line, NULL, 10); + + // if `strtol` fails, it apparently just returns 0, how helpful + if (left == 0 && right == 0) { + break; + } + + nums_l[nlines] = left; + nums_r[nlines] = right; + + nlines++; + } + + qsort(nums_l, nlines, 4, cmp); + qsort(nums_r, nlines, 4, cmp); + + int solution_1 = part1(nums_l, nums_r, nlines); + printf("Part 1: %i\n", solution_1); + + int solution_2 = part2(nums_l, nums_r, nlines); + printf("Part 2: %i\n", solution_2); +}