aocpp/2022/01.cpp

93 lines
2.1 KiB
C++
Raw Normal View History

2022-12-02 09:34:16 -08:00
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <sstream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <vector>
#include <doctest.h>
#include <aocpp/Startup.hpp>
namespace {
using Input = std::vector<std::vector<std::int64_t>>;
/// @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<std::int64_t, std::int64_t>
{
2023-01-25 15:14:30 -08:00
if (input.size() < 3) {
throw std::runtime_error{"bad input"};
}
2022-12-02 09:34:16 -08:00
std::vector<std::int64_t> elves;
2023-01-25 15:14:30 -08:00
std::transform(
input.begin(), input.end(), std::back_inserter(elves),
[](auto const& elf){
return std::reduce(elf.begin(), elf.end());
});
2022-12-02 09:34:16 -08:00
2023-01-25 15:14:30 -08:00
// 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());
2022-12-02 09:34:16 -08:00
2023-01-25 15:14:30 -08:00
auto const p1 = elves.front();
auto const p2 = std::reduce(elves.begin(), top3);
return {p1, p2};
2022-12-02 09:34:16 -08:00
}
} // 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"};
2023-01-25 15:14:30 -08:00
auto const entries = Parse(in);
auto const [p1,p2] = Solve(entries);
2022-12-02 09:34:16 -08:00
CHECK(p1 == 24000);
CHECK(p2 == 45000);
}
}
2023-01-31 09:15:15 -08:00
auto Main(std::istream & in, std::ostream & out) -> void
2023-01-31 08:58:42 -08:00
{
auto const [p1,p2] = Solve(Parse(in));
2023-01-31 09:15:15 -08:00
out << "Part 1: " << p1 << std::endl;
out << "Part 2: " << p2 << std::endl;
2022-12-02 09:34:16 -08:00
}