update 22

This commit is contained in:
2024-09-02 15:20:25 -07:00
parent 9aa821376c
commit 9e6223f886
4 changed files with 300 additions and 18 deletions

View File

@@ -1,7 +1,8 @@
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
@@ -11,17 +12,18 @@
#include <aocpp/Startup.hpp>
#include <aocpp/Coord.hpp>
auto Part1(aocpp::Grid const &input) -> std::int64_t
auto Part1(aocpp::Grid const &input, std::int64_t reps = 10'000) -> std::int64_t
{
std::unordered_set<aocpp::Coord> infected;
// Initialize set of infected locations
input.each([&infected](auto const pos, auto const cell)
{
{
if (cell == '#')
{
infected.insert(pos);
} });
}
});
// Start in the middle
aocpp::Coord pos;
@@ -34,20 +36,19 @@ auto Part1(aocpp::Grid const &input) -> std::int64_t
// Count the number of iterations that cause an infection
std::uint64_t infections = 0;
for (int i = 0; i < 10'000; ++i)
while (reps --> 0)
{
auto const it = infected.find(pos);
if (it == end(infected))
auto const [it, added] = infected.insert(pos);
if (added)
{
// was clean
vel = CCW(vel); // turn "left"
infected.insert(pos); // infect
vel = CCW(vel); // turn "left"
infections++;
}
else
{
// was infected
vel = CW(vel); // turn "right"
vel = CW(vel); // turn "right"
infected.erase(it); // clean
}
pos += vel; // advance
@@ -56,17 +57,18 @@ auto Part1(aocpp::Grid const &input) -> std::int64_t
return infections;
}
auto Part2(aocpp::Grid const &input) -> std::int64_t
auto Part2(aocpp::Grid const &input, std::int64_t reps = 10'000'000) -> std::int64_t
{
std::unordered_map<aocpp::Coord, char> cells;
// Initialize set of infected locations
input.each([&cells](auto const pos, auto const cell)
{
{
if (cell == '#')
{
cells.try_emplace(pos, '#');
} });
}
});
// Start in the middle
aocpp::Coord pos;
@@ -79,7 +81,7 @@ auto Part2(aocpp::Grid const &input) -> std::int64_t
// Count the number of iterations that cause an infection
std::uint64_t infections = 0;
for (int i = 0; i < 10'000'000; ++i)
while (reps --> 0)
{
auto const [it, added] = cells.try_emplace(pos, 'W'); // clean becomes weakened
if (added)
@@ -118,9 +120,24 @@ TEST_SUITE("2017-22 examples")
{
TEST_CASE("part 1")
{
std::istringstream in{
"..#\n"
"#..\n"
"...\n"};
auto const input = aocpp::Grid::Parse(in);
CHECK(5 == Part1(input, 7));
CHECK(41 == Part1(input, 70));
CHECK(5587 == Part1(input, 10'000));
}
TEST_CASE("part 2")
{
std::istringstream in{
"..#\n"
"#..\n"
"...\n"};
auto const input = aocpp::Grid::Parse(in);
CHECK(26 == Part2(input, 100));
CHECK(2'511'944 == Part2(input, 10'000'000));
}
}