aocpp/2022/09.cpp

106 lines
2.0 KiB
C++
Raw Normal View History

2023-01-23 10:06:53 -08:00
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <set>
#include <sstream>
#include <tuple>
#include <doctest.h>
#include <aocpp/Coord.hpp>
#include <aocpp/Startup.hpp>
using namespace aocpp;
namespace {
2023-01-24 09:01:42 -08:00
using DirFn = Coord(Coord);
2023-01-23 10:06:53 -08:00
2023-01-24 09:01:42 -08:00
auto ToDir(char c) -> DirFn* {
2023-01-23 10:06:53 -08:00
switch (c) {
case 'L': return Left;
case 'R': return Right;
case 'D': return Down;
case 'U': return Up;
default: throw std::runtime_error{"bad input"};
}
}
/// @brief Return the sign of the number
/// @param x number
/// @return -1, 0, or 1 matching the sign of the input
auto Sign(std::int64_t x) -> std::int64_t
{
return (x>0) - (x<0);
}
2023-01-24 09:01:42 -08:00
class Logic {
Coord knots[10] {}; // Current location of each knot in the rope
std::set<Coord> s1{{}}, s9{{}};
2023-01-23 10:06:53 -08:00
2023-01-24 09:01:42 -08:00
public:
auto answer() const -> std::pair<std::size_t, std::size_t>
{
return {s1.size(), s9.size()};
}
auto move(DirFn* dirFn) -> void
{
knots[0] = dirFn(knots[0]);
std::size_t k;
for (k = 1; k < 10; ++k) {
auto const delta {knots[k-1] - knots[k]};
if (NormInf(delta) <= 1) {
break;
2023-01-23 10:06:53 -08:00
}
2023-01-24 09:01:42 -08:00
knots[k] += {Sign(delta.x), Sign(delta.y)};
}
2023-01-23 10:06:53 -08:00
2023-01-24 09:01:42 -08:00
// only update the sets when a knot actually moved
if (k > 1) {
s1.insert(knots[1]);
if (k > 9) {
s9.insert(knots[9]);
2023-01-23 10:06:53 -08:00
}
}
}
2023-01-24 09:01:42 -08:00
};
2023-01-23 10:06:53 -08:00
2023-01-24 09:01:42 -08:00
auto Solve(std::istream & in) -> std::pair<std::size_t, std::size_t>
{
Logic logic;
char d;
std::size_t n;
while (in >> d >> n) {
while (n--) { logic.move(ToDir(d)); }
}
return logic.answer();
2023-01-23 10:06:53 -08:00
}
} // namespace
TEST_SUITE("2022-09 examples") {
TEST_CASE("example") {
std::istringstream in {
"R 5\n"
"U 8\n"
"L 8\n"
"D 3\n"
"R 17\n"
"D 10\n"
"L 25\n"
"U 20\n"};
auto [p1,p2] = Solve(in);
CHECK(p1 == 88);
CHECK(p2 == 36);
}
}
2023-01-31 09:15:15 -08:00
auto Main(std::istream & in, std::ostream & out) -> void
2023-01-23 10:06:53 -08:00
{
2023-01-31 08:58:42 -08:00
auto const [p1,p2] = Solve(in);
2023-01-31 09:15:15 -08:00
out << "Part 1: " << p1 << std::endl;
out << "Part 2: " << p2 << std::endl;
2023-01-23 10:06:53 -08:00
}