AmendHub

Download

schrockwell

/

aoc2024

/

day1.c

 

(View History)

schrockwell   Day 1 solution and example input Latest amendment: 1 on 2024-12-08

1 #include <console.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 // CONSTANTS
6
7 #define MAX_LINE_LENGTH 32
8 #define MAX_LIST_SIZE 1024
9
10 // TYPES
11
12 typedef struct {
13 long int key;
14 int value;
15 } kv;
16
17 // GLOBALS
18
19 long int firstList[MAX_LIST_SIZE];
20 long int secondList[MAX_LIST_SIZE];
21
22 kv secondHist[MAX_LIST_SIZE];
23
24 // FUNCTIONS
25
26 int compare_longs(const void *a, const void *b) {
27 long int int_a = *(const long int *)a;
28 long int int_b = *(const long int *)b;
29
30 if (int_a < int_b) return -1;
31 if (int_a > int_b) return 1;
32 return 0;
33 }
34
35 int build_histogram(kv hist[], long int arr[], int count) {
36 int i = 0;
37 int keyCount = 0;
38
39 for (i = 0; i < count; i++) {
40 long int key = arr[i];
41 int histIndex = findHistIndex(hist, keyCount, key);
42
43 if (histIndex == -1) {
44 histIndex = keyCount;
45 keyCount++;
46 }
47
48 hist[histIndex].key = key;
49 hist[histIndex].value++;
50 }
51
52 return keyCount;
53 }
54
55 int findHistIndex(kv hist[], int count, long int key) {
56 int i = 0;
57
58 for (i = 0; i < count; i++) {
59 if (hist[i].key == key) {
60 return i;
61 }
62 }
63
64 return -1;
65 }
66
67 void main(int argc, char* argv) {
68 //char *filename = "01-input.txt";
69 char *filename = "01-example.txt";
70
71 int index = 0;
72 long int firstAnswer = 0;
73 long int secondAnswer = 0;
74 int i = 0;
75 int histCount, histIndex;
76
77 FILE *file;
78 char line[MAX_LINE_LENGTH];
79
80 file = fopen(filename, "r");
81 if (file == NULL) {
82 perror("Error opening file");
83 return;
84 }
85
86 printf("Reading %s... ", filename);
87
88 while (fgets(line, sizeof(line), file) != NULL) {
89 long int num1, num2;
90 if (sscanf(line, "%ld %ld", &num1, &num2) != 2) {
91 printf("error parsing line %d", index);
92 return;
93 }
94
95 firstList[index] = num1;
96 secondList[index] = num2;
97 index++;
98 }
99
100 fclose(file);
101
102 printf("read %d lines\n", index);
103
104 // PART 1
105
106 printf("Sorting first list...\n");
107 qsort(firstList, index, sizeof(long int), compare_longs);
108
109 printf("Sorting second list...\n");
110 qsort(secondList, index, sizeof(long int), compare_longs);
111
112 for (i = 0; i < index; i++) {
113 firstAnswer = firstAnswer + abs(firstList[i] - secondList[i]);
114 }
115
116 // PART 2
117
118 printf("Calculating histogram...\n");
119 histCount = build_histogram(secondHist, secondList, index);
120
121 //for (i = 0; i < histCount; i++) {
122 // printf("%ld => %d\n", secondHist[i].key, secondHist[i].value);
123 //}
124
125 for (i = 0; i < index; i++) {
126 histIndex = findHistIndex(secondHist, histCount, firstList[i]);
127 if (histIndex == -1) continue;
128
129 secondAnswer += firstList[i] * secondHist[histIndex].value;
130 }
131
132 printf("Part 1: %ld\n", firstAnswer);
133 printf("Part 2: %ld\n", secondAnswer);
134 }