parameterize 2024-7's solving function

This commit is contained in:
Eric Mertens 2024-12-28 19:35:53 -06:00
parent 0af607bc92
commit 8e399f37d0

View File

@ -15,7 +15,15 @@ namespace qi = boost::spirit::qi;
namespace {
auto drop_suffix(std::uint64_t x, std::uint64_t y) -> std::optional<std::uint64_t>
auto try_subtract(std::uint64_t t, std::uint64_t x) -> std::optional<std::uint64_t> {
return x < t ? std::optional{t - x} : std::nullopt;
}
auto try_divide(std::uint64_t t, std::uint64_t x) -> std::optional<std::uint64_t> {
return t % x == 0 ? std::optional{t / x} : std::nullopt;
}
auto try_unsuffix(std::uint64_t x, std::uint64_t y) -> std::optional<std::uint64_t>
{
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<std::uint64_
}
auto calibrated(
bool const part2,
std::uint64_t const target,
std::vector<std::uint64_t> const& numbers
std::vector<std::uint64_t> 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"