From d6b170e274ff44a07bb3e07c84b7a1381cf96dd8 Mon Sep 17 00:00:00 2001 From: Bananymous Date: Sun, 1 Dec 2024 07:38:21 +0200 Subject: [PATCH] aoc2024: implement day1 solution --- userspace/aoc2024/CMakeLists.txt | 1 + userspace/aoc2024/day1/CMakeLists.txt | 9 +++ userspace/aoc2024/day1/main.cpp | 101 ++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 userspace/aoc2024/day1/CMakeLists.txt create mode 100644 userspace/aoc2024/day1/main.cpp diff --git a/userspace/aoc2024/CMakeLists.txt b/userspace/aoc2024/CMakeLists.txt index e1ceed66..dde0c76b 100644 --- a/userspace/aoc2024/CMakeLists.txt +++ b/userspace/aoc2024/CMakeLists.txt @@ -1,4 +1,5 @@ set(AOC2024_PROJECTS + day1 full ) diff --git a/userspace/aoc2024/day1/CMakeLists.txt b/userspace/aoc2024/day1/CMakeLists.txt new file mode 100644 index 00000000..4ed6be3a --- /dev/null +++ b/userspace/aoc2024/day1/CMakeLists.txt @@ -0,0 +1,9 @@ +set(SOURCES + main.cpp +) + +add_executable(aoc2024_day1 ${SOURCES}) +banan_include_headers(aoc2024_day1 ban) +banan_link_library(aoc2024_day1 libc) + +install(TARGETS aoc2024_day1 OPTIONAL) diff --git a/userspace/aoc2024/day1/main.cpp b/userspace/aoc2024/day1/main.cpp new file mode 100644 index 00000000..39af86ca --- /dev/null +++ b/userspace/aoc2024/day1/main.cpp @@ -0,0 +1,101 @@ +#include +#include +#include + +#include +#include + +using i8 = int8_t; +using i16 = int16_t; +using i32 = int32_t; +using i64 = int64_t; + +using u8 = uint8_t; +using u16 = uint16_t; +using u32 = uint32_t; +using u64 = uint64_t; + +i64 part1(FILE* fp) +{ + BAN::Vector lhs; + BAN::Vector rhs; + + for (;;) { + i64 l, r; + if (fscanf(fp, "%" SCNd64 " %" SCNd64 "\n", &l, &r) != 2) + break; + MUST(lhs.push_back(l)); + MUST(rhs.push_back(r)); + } + + BAN::sort::sort(lhs.begin(), lhs.end()); + BAN::sort::sort(rhs.begin(), rhs.end()); + + i64 result = 0; + for (size_t i = 0; i < lhs.size(); i++) + result += BAN::Math::abs(lhs[i] - rhs[i]); + + return result; +} + +i64 part2(FILE* fp) +{ + BAN::HashMap lhs; + BAN::HashMap rhs; + + for (;;) { + i64 l, r; + if (fscanf(fp, "%" SCNd64 " %" SCNd64 "\n", &l, &r) != 2) + break; + + { + auto it = lhs.find(l); + if (it == lhs.end()) + MUST(lhs.insert(l, 1)); + else + it->value++; + } + + { + auto it = rhs.find(r); + if (it == rhs.end()) + MUST(rhs.insert(r, 1)); + else + it->value++; + } + } + + i64 result = 0; + + for (auto [id, count] : lhs) { + auto it = rhs.find(id); + if (it == rhs.end()) + continue; + result += id * count * it->value; + } + + return result; +} + +int main(int argc, char** argv) +{ + const char* file_path = "/usr/share/aoc2024/day1_input.txt"; + + if (argc >= 2) + file_path = argv[1]; + + FILE* fp = fopen(file_path, "r"); + if (fp == nullptr) + { + perror("fopen"); + return 1; + } + + printf("part1: %" PRId64 "\n", part1(fp)); + + fseek(fp, 0, SEEK_SET); + + printf("part2: %" PRId64 "\n", part2(fp)); + + fclose(fp); +}