advent_of_code/day_1/1.c

79 lines
1.5 KiB
C

#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 + 1) * sizeof(int));
// haha pointer arithmetic go brrr
int* right = left + lineCount;
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++) {
size_t leftMin = i;
size_t 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;
}