92 lines
2.1 KiB
C++
92 lines
2.1 KiB
C++
#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>
|
|
{
|
|
if (input.size() < 3) {
|
|
throw std::runtime_error{"bad input"};
|
|
}
|
|
|
|
std::vector<std::int64_t> 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(int argc, char** argv) -> int {
|
|
auto const [p1,p2] = Solve(Parse(*aocpp::Startup(argc, argv)));
|
|
std::cout << "Part 1: " << p1 << std::endl;
|
|
std::cout << "Part 2: " << p2 << std::endl;
|
|
}
|