diff --git a/2022/06.cpp b/2022/06.cpp new file mode 100644 index 0000000..60b5bdc --- /dev/null +++ b/2022/06.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace { + +auto Solve(std::string const& input, std::size_t n) -> std::size_t +{ + std::array counts {}; + std::size_t uniques {0}; + + auto const inc = [&](char c) { + if (0 == counts[static_cast(c)]++) { + uniques++; + } + }; + + auto const dec = [&](char c) { + if (0 == --counts[static_cast(c)]) { + uniques--; + } + }; + + for (std::size_t i = 0; i < n; ++i) { + inc(input[i]); + } + + for (std::size_t i = n; i < input.size(); ++i) { + dec(input[i-n]); + inc(input[i]); + if (uniques == n) { return i+1; } + } + + throw std::runtime_error{"bad input"}; +} + +} // namespace + +TEST_SUITE("2022-06 examples") { + TEST_CASE("examples") { + CHECK(Solve("bvwbjplbgvbhsrlpgdmjqwftvncz", 4) == 5); + CHECK(Solve("nppdvjthqldpwncqszvftbrmjlhg", 4) == 6); + CHECK(Solve("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 4) == 10); + CHECK(Solve("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 4) == 11); + + CHECK(Solve("mjqjpqmgbljsphdztnvjfqwrcgsmlb", 14) == 19); + CHECK(Solve("bvwbjplbgvbhsrlpgdmjqwftvncz", 14) == 23); + CHECK(Solve("nppdvjthqldpwncqszvftbrmjlhg", 14) == 23); + CHECK(Solve("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", 14) == 29); + CHECK(Solve("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw", 14) == 26); + } +} + +auto main(int argc, char** argv) -> int { + std::string input; + std::getline(*aocpp::Startup(argc, argv), input); + std::cout << "Part 1: " << Solve(input, 4) << std::endl; + std::cout << "Part 2: " << Solve(input, 14) << std::endl; +} diff --git a/2022/CMakeLists.txt b/2022/CMakeLists.txt index a291217..ec51db3 100644 --- a/2022/CMakeLists.txt +++ b/2022/CMakeLists.txt @@ -7,6 +7,9 @@ target_link_libraries(2022_03 aocpp) add_executable(2022_04 04.cpp) target_link_libraries(2022_04 aocpp) +add_executable(2022_06 06.cpp) +target_link_libraries(2022_06 aocpp) + add_executable(2022_08 08.cpp) target_link_libraries(2022_08 aocpp)