advent/2024/01.c

80 lines
1.6 KiB
C
Raw Normal View History

2024-12-02 09:58:45 -05:00
#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);
}