From d3525c097bf75751f7d7c90cfe9e7f2602e67314 Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Fri, 2 Dec 2022 09:34:16 -0800 Subject: [PATCH] 2022-01 --- 2022/01.cpp | 83 +++++++++++++++++++++++++++++++++++++++++++++ 2022/CMakeLists.txt | 2 ++ CMakeLists.txt | 1 + 3 files changed, 86 insertions(+) create mode 100644 2022/01.cpp create mode 100644 2022/CMakeLists.txt diff --git a/2022/01.cpp b/2022/01.cpp new file mode 100644 index 0000000..db0067e --- /dev/null +++ b/2022/01.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace { + +using Input = std::vector>; + +/// @brief Parse the input stream as a newline-delimited list of lists of integers +/// @param in input file parsed until EOF +/// @return outer list of elves, inner lists of calories +auto Parse(std::istream & in) -> Input +{ + Input result {{}}; + std::string line; + while (std::getline(in, line)) { + if (line.empty()) { + result.push_back({}); + } else { + result.back().emplace_back(std::stoll(line)); + } + } + return result; +} + +/// @brief Compute the top calorie carrying elves +/// @param input List of elves each with a list of calories +/// @return top 1 and sum of top 3 calorie counts +auto Solve(Input const& input) -> std::pair +{ + if (input.size() < 3) { throw std::runtime_error{"bad input"}; } + + std::vector elves; + for (auto const& elf : input) { + elves.push_back(std::reduce(elf.begin(), elf.end())); + } + + std::partial_sort(elves.begin(), std::next(elves.begin(), 3), elves.end(), std::greater()); + + return {elves.front(), std::reduce(elves.begin(), std::next(elves.begin(), 3))}; +} + +} // namespace + +TEST_SUITE("2022-01 examples") { + TEST_CASE("example") { + std::istringstream in { + "1000\n" + "2000\n" + "3000\n" + "\n" + "4000\n" + "\n" + "5000\n" + "6000\n" + "\n" + "7000\n" + "8000\n" + "9000\n" + "\n" + "10000\n"}; + auto entries = Parse(in); + auto [p1,p2] = Solve(entries); + CHECK(p1 == 24000); + CHECK(p2 == 45000); + } +} + +auto main(int argc, char** argv) -> int { + auto [p1,p2] = Solve(Parse(*aocpp::Startup(argc, argv))); + std::cout << "Part 1: " << p1 << std::endl; + std::cout << "Part 2: " << p2 << std::endl; +} diff --git a/2022/CMakeLists.txt b/2022/CMakeLists.txt new file mode 100644 index 0000000..d4d59db --- /dev/null +++ b/2022/CMakeLists.txt @@ -0,0 +1,2 @@ +add_executable(2022_01 01.cpp) +target_link_libraries(2022_01 aocpp) diff --git a/CMakeLists.txt b/CMakeLists.txt index be8052a..1e45604 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,3 +28,4 @@ add_subdirectory(2017) add_subdirectory(2018) add_subdirectory(2019) add_subdirectory(2020) +add_subdirectory(2022)