diff --git a/2022/06.cpp b/2022/06.cpp index 60b5bdc..19b69fb 100644 --- a/2022/06.cpp +++ b/2022/06.cpp @@ -18,15 +18,11 @@ auto Solve(std::string const& input, std::size_t n) -> std::size_t std::size_t uniques {0}; auto const inc = [&](char c) { - if (0 == counts[static_cast(c)]++) { - uniques++; - } + uniques += 1 == ++counts[static_cast(c)]; }; auto const dec = [&](char c) { - if (0 == --counts[static_cast(c)]) { - uniques--; - } + uniques -= 0 == --counts[static_cast(c)]; }; for (std::size_t i = 0; i < n; ++i) { diff --git a/2022/09.cpp b/2022/09.cpp index 7b84acf..ef438c9 100644 --- a/2022/09.cpp +++ b/2022/09.cpp @@ -15,9 +15,9 @@ using namespace aocpp; namespace { -using Dir = Coord(*)(Coord); +using DirFn = Coord(Coord); -auto ToDir(char c) -> Dir { +auto ToDir(char c) -> DirFn* { switch (c) { case 'L': return Left; case 'R': return Right; @@ -35,38 +35,48 @@ auto Sign(std::int64_t x) -> std::int64_t return (x>0) - (x<0); } -auto Solve(std::istream & in) -> std::pair -{ - std::size_t constexpr knotn {10}; - Coord knots[knotn] {}; - std::set p1{knots[1]}, p2{knots[9]}; - char d; - long n; +class Logic { + Coord knots[10] {}; // Current location of each knot in the rope + std::set s1{{}}, s9{{}}; - while (in >> d >> n) { - auto const dir = ToDir(d); - while (n--) { - knots[0] = dir(knots[0]); - - std::size_t k; - for (k = 1; k < knotn; ++k) { - auto const delta {knots[k-1] - knots[k]}; - if (NormInf(delta) <= 1) { - break; - } - knots[k] += {Sign(delta.x), Sign(delta.y)}; +public: + auto answer() const -> std::pair + { + 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; } + knots[k] += {Sign(delta.x), Sign(delta.y)}; + } - if (k > 1) { - p1.insert(knots[1]); - if (k > 9) { - p2.insert(knots[9]); - } + // only update the sets when a knot actually moved + if (k > 1) { + s1.insert(knots[1]); + if (k > 9) { + s9.insert(knots[9]); } } } +}; - return {p1.size(), p2.size()}; +auto Solve(std::istream & in) -> std::pair +{ + Logic logic; + char d; + std::size_t n; + while (in >> d >> n) { + while (n--) { logic.move(ToDir(d)); } + } + return logic.answer(); } } // namespace diff --git a/2022/20.cpp b/2022/20.cpp index a40c0fa..879d1e7 100644 --- a/2022/20.cpp +++ b/2022/20.cpp @@ -33,10 +33,8 @@ auto Solve(Input const& input, std::size_t const rounds) -> std::int64_t std::size_t const len = input.size(); std::vector fwds(len), bwds(len); - for (std::size_t i = 0; i < len; ++i) { - fwds[i] = aocpp::Mod(i+1, len); - bwds[i] = aocpp::Mod(i-1, len); - } + std::iota(fwds.begin(), fwds.end()-1, 1); fwds.back() = 0; + std::iota(bwds.begin()+1, bwds.end(), 0); bwds.front() = len-1; for (std::size_t r = 0; r < rounds; ++r) { for (std::size_t i = 0; i < len; ++i) {