add 2024 day 1
This commit is contained in:
parent
9ef31dde55
commit
1f6d987c53
2
.gitignore
vendored
2
.gitignore
vendored
@ -1,3 +1,5 @@
|
||||
*/data/*
|
||||
*/target/*
|
||||
**.exe
|
||||
|
||||
*.out
|
||||
|
79
2024/01.c
Normal file
79
2024/01.c
Normal file
@ -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);
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user