day 1 part 1

This commit is contained in:
Parker Macdonald 2024-12-07 13:56:24 -07:00
parent c9055b6ff4
commit a50fdca40d

79
day 1/day1.c Normal file
View file

@ -0,0 +1,79 @@
#include <stdlib.h>
#include <stdio.h>
#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
int* left = malloc(lineCount * 2 * sizeof(int));
// haha pointer arithmetic go brrr
int* right = left + lineCount * sizeof(int);
for (size_t i = 0; i < lineCount; i++) {
int leftNum, rightNum;
int numsGot = fscanf(fp, "%d %d\n", &leftNum, &rightNum);
if (numsGot == 2) {
left[i] = leftNum;
right[i] = rightNum;
}
}
for (size_t i = 0; i < lineCount - 1; i++) {
int leftMin = i;
int rightMin = i;
for (size_t j = i + 1; j < lineCount; j++) {
if (left[j] < left[leftMin]) {
leftMin = j;
}
if (right[j] < right[rightMin]) {
rightMin = j;
}
}
if (leftMin != i) {
int temp = left[i];
left[i] = left[leftMin];
left[leftMin] = temp;
}
if (rightMin != i) {
int temp = right[i];
right[i] = right[rightMin];
right[rightMin] = temp;
}
}
int sum = 0;
for (size_t i = 0; i < lineCount; i++) {
sum += abs(left[i] - right[i]);
}
printf("%d\n", sum);
free(left);
fclose(fp);
return 0;
}