#include #include #include #include #include #include #include namespace { // Parses the numbers and returns them in sorted order auto Parse(std::istream & in) -> std::vector { std::vector result; std::int64_t value; while (in >> value) { result.push_back(value); } std::sort(result.begin(), result.end()); return result; } auto Part1(std::vector 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 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; }