2022-11-20 21:31:38 -08:00
|
|
|
#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)));
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
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 adapters {Parse(in)};
|
2023-01-31 09:15:15 -08:00
|
|
|
out << "Part 1: " << Part1(adapters) << std::endl;
|
|
|
|
out << "Part 2: " << Part2(adapters) << std::endl;
|
2022-11-20 21:31:38 -08:00
|
|
|
}
|