#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; std::transform( input.begin(), input.end(), std::back_inserter(elves), [](auto const& elf){ return std::reduce(elf.begin(), elf.end()); }); // Fill the top 3 array elements with the maximum values auto const top3 = std::next(elves.begin(), 3); std::partial_sort(elves.begin(), top3, elves.end(), std::greater()); auto const p1 = elves.front(); auto const p2 = std::reduce(elves.begin(), top3); return {p1, p2}; } } // 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 const entries = Parse(in); auto const [p1,p2] = Solve(entries); CHECK(p1 == 24000); CHECK(p2 == 45000); } } auto Main(std::istream & in, std::ostream & out) -> void { auto const [p1,p2] = Solve(Parse(in)); out << "Part 1: " << p1 << std::endl; out << "Part 2: " << p2 << std::endl; }