diff --git a/2024/07.cpp b/2024/07.cpp index 3f8bfc4..474d819 100644 --- a/2024/07.cpp +++ b/2024/07.cpp @@ -15,7 +15,15 @@ namespace qi = boost::spirit::qi; namespace { -auto drop_suffix(std::uint64_t x, std::uint64_t y) -> std::optional +auto try_subtract(std::uint64_t t, std::uint64_t x) -> std::optional { + return x < t ? std::optional{t - x} : std::nullopt; +} + +auto try_divide(std::uint64_t t, std::uint64_t x) -> std::optional { + return t % x == 0 ? std::optional{t / x} : std::nullopt; +} + +auto try_unsuffix(std::uint64_t x, std::uint64_t y) -> std::optional { while (x > 0) { if (y == 0) { return x; } @@ -27,9 +35,9 @@ auto drop_suffix(std::uint64_t x, std::uint64_t y) -> std::optional const& numbers + std::vector const& numbers, + auto... ops ) -> bool { if (numbers.empty()) { return false; } @@ -45,13 +53,11 @@ auto calibrated( if (i == 0) { if (x == t) { return true; } } else { - if (x < t) { work.emplace(i - 1, t - x); } - if (t % x == 0) { work.emplace(i - 1, t / x); } - if (part2) { - if (auto const u = drop_suffix(t, x)) { + ([&](auto const op) { + if (auto const u = op(t, x)) { work.emplace(i - 1, *u); } - } + }(ops), ...); } } @@ -69,8 +75,8 @@ auto Main(std::istream & in, std::ostream & out) -> void std::uint64_t p1 = 0, p2 = 0; for (auto && [x, xs] : input) { - if (calibrated(false, x, xs)) p1 += x; - if (calibrated(true, x, xs)) p2 += x; + if (calibrated(x, xs, try_subtract, try_divide)) p1 += x; + if (calibrated(x, xs, try_subtract, try_divide, try_unsuffix)) p2 += x; } out << "Part 1: " << p1 << "\n"