aocpp/2020/10.cpp
2022-11-20 21:31:38 -08:00

83 lines
2.1 KiB
C++

#include <cstdint>
#include <iostream>
#include <sstream>
#include <tuple>
#include <vector>
#include <doctest.h>
#include <aocpp/Startup.hpp>
namespace {
// Parses the numbers and returns them in sorted order
auto Parse(std::istream & in) -> std::vector<std::int64_t>
{
std::vector<std::int64_t> result;
std::int64_t value;
while (in >> value) {
result.push_back(value);
}
std::sort(result.begin(), result.end());
return result;
}
auto Part1(std::vector<std::int64_t> const& adapters) -> std::size_t
{
std::int64_t prev{0};
std::size_t ones{0}, threes{1};
if (adapters.empty()) return 0;
for (auto const x : adapters) {
switch (x - prev) {
case 1: ones++; break;
case 3: threes++; break;
}
prev = x;
}
return ones * threes;
}
auto Part2(std::vector<std::int64_t> const& adapters) -> std::size_t
{
std::size_t n1{1}, n2{0}, n3{0};
std::int64_t prev{0};
for (auto const x : adapters) {
switch(x - prev) {
case 1: std::tie(n1,n2,n3) = std::make_tuple(n1+n2+n3, n1, n2); break;
case 2: std::tie(n1,n2,n3) = std::make_tuple(n1+n2, 0, n1); break;
case 3: std::tie(n1,n2,n3) = std::make_tuple(n1, 0, 0); break;
default: std::tie(n1,n2,n3) = std::make_tuple(0 , 0, 0); break;
}
prev = x;
}
return n1;
}
} // namespace
TEST_SUITE("documented examples") {
TEST_CASE("part 1") {
std::istringstream in {"16 10 15 5 1 11 7 19 6 12 4"};
REQUIRE(Part1(Parse(in)) == 7*5);
in = std::istringstream{"28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 "};
REQUIRE(Part1(Parse(in)) == 22*10);
}
TEST_CASE("part 2") {
std::istringstream in {"16 10 15 5 1 11 7 19 6 12 4"};
REQUIRE(8 == Part2(Parse(in)));
in = std::istringstream{"28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 "};
REQUIRE(19208 == Part2(Parse(in)));
}
}
auto main(int argc, char** argv) -> int {
auto adapters = Parse(aocpp::Startup(argc, argv));
std::cout << "Part 1: " << Part1(adapters) << std::endl;
std::cout << "Part 2: " << Part2(adapters) << std::endl;
}