summaryrefslogtreecommitdiff
path: root/01bis.c
diff options
context:
space:
mode:
authorVincent Douillet <vincent@vdouillet.fr>2022-12-01 20:35:58 +0100
committerVincent Douillet <vincent@vdouillet.fr>2022-12-01 20:35:58 +0100
commit076d2ca0e0c2f0308373628272a3972241575653 (patch)
treebf60b98fe6b5a569649f41ff93836a9623a93c18 /01bis.c
day 1
Diffstat (limited to '01bis.c')
-rw-r--r--01bis.c58
1 files changed, 58 insertions, 0 deletions
diff --git a/01bis.c b/01bis.c
new file mode 100644
index 0000000..e2bbb8a
--- /dev/null
+++ b/01bis.c
@@ -0,0 +1,58 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <err.h>
+#include "input.h"
+
+#define INPUT "input/01.txt"
+#define MAX_ELF 2000
+#define EXPECTED1 70369L
+#define EXPECTED2 203002L
+
+int cmp_calorie(const void* a, const void* b) {
+ return *(int*)b - *(int*)a;
+}
+
+int main() {
+ // read input
+ struct input_str input;
+ input_str_read(&input, INPUT);
+
+ // compute each elf calorie count
+ long elf_calories[MAX_ELF];
+ int elf_count = 0;
+ long elf_calorie = 0;
+ for(size_t i = 0; i < input.line_count; i++) {
+ if(*(input.lines[i]) == '\n') {
+ elf_calories[elf_count] = elf_calorie;
+ elf_count++;
+ if(elf_count >= MAX_ELF)
+ err(2, "elf overflow!");
+ elf_calorie = 0;
+ }
+ else {
+ int snack_calories = atoi(input.lines[i]);
+ elf_calorie += snack_calories;
+ }
+ }
+ elf_calories[elf_count] = elf_calorie;
+ elf_count++;
+ if(elf_count >= MAX_ELF)
+ err(2, "elf overflow!");
+
+ // sort calories from highest to lowest
+ qsort(elf_calories, elf_count, sizeof(long), cmp_calorie);
+
+ // part 1
+ if(elf_count < 1)
+ err(2, "insufficent elves!");
+ CHECK(elf_calories[0], EXPECTED1)
+
+ // part 2
+ if(elf_count < 3)
+ err(2, "insufficent elves!");
+ CHECK(elf_calories[0] + elf_calories[1] + elf_calories[2], EXPECTED2)
+
+ // cleanup & exit
+ input_str_free(&input);
+ return 0;
+}