From 2a5578bc4d5ef5407a4dc12919d91bbbffd1e174 Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Fri, 2 Dec 2022 08:52:03 +0100 Subject: [PATCH] Advent of code day 1 --- day1_1.c3 | 33 +++++++++++++++++++++++++++++++++ day1_2.c3 | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 day1_1.c3 create mode 100644 day1_2.c3 diff --git a/day1_1.c3 b/day1_1.c3 new file mode 100644 index 0000000..4ad538a --- /dev/null +++ b/day1_1.c3 @@ -0,0 +1,33 @@ +import std::io; +import libc; + +fn void main() +{ + File f; + f.open("calories.txt", "rb")!!; + defer catch(f.close()); + usz current_entry = 0; + usz max_entry = 0; + usz max_elf = 1; + usz index_elf = 1; + while (!f.eof()) + { + @pool() + { + char[] line = f.tgetline(); + if (!line.len) + { + current_entry = 0; + index_elf++; + continue; + } + current_entry += str::to_int(line)!!; + if (current_entry > max_entry) + { + max_elf = index_elf; + max_entry = current_entry; + } + }; + } + io::printfln("Elf #%d carries the most calories (%d)", max_elf, max_entry); +} diff --git a/day1_2.c3 b/day1_2.c3 new file mode 100644 index 0000000..6fc3403 --- /dev/null +++ b/day1_2.c3 @@ -0,0 +1,45 @@ +import std::io; + +int[3] entry_max; + +fn void update_max(int entry) +{ + for (int i = 0; i < 3; i++) + { + if (entry > entry_max[i]) + { + for (int j = 2; j > i; j--) + { + entry_max[j] = entry_max[j - 1]; + } + entry_max[i] = entry; + return; + } + } +} + +fn void main() +{ + File f; + f.open("calories.txt", "rb")!!; + defer catch(f.close()); + int current_entry = 0; + while (!f.eof()) + { + @pool() + { + char[] line = f.tgetline(); + if (!line.len) + { + update_max(current_entry); + current_entry = 0; + continue; + } + current_entry += str::to_int(line)!!; + }; + } + if (current_entry) update_max(current_entry); + int sum = 0; + foreach (val : entry_max) sum += val; + io::printfln("Top three elves carries: %d", sum); +}