diff --git a/day 1/day1.c b/day 1/day1.c new file mode 100644 index 0000000..9a38b27 --- /dev/null +++ b/day 1/day1.c @@ -0,0 +1,79 @@ +#include +#include + +#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; +} \ No newline at end of file