parameterize 2024-7's solving function
This commit is contained in:
parent
0af607bc92
commit
8e399f37d0
26
2024/07.cpp
26
2024/07.cpp
@ -15,7 +15,15 @@ namespace qi = boost::spirit::qi;
|
|||||||
|
|
||||||
namespace {
|
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) {
|
while (x > 0) {
|
||||||
if (y == 0) { return x; }
|
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(
|
auto calibrated(
|
||||||
bool const part2,
|
|
||||||
std::uint64_t const target,
|
std::uint64_t const target,
|
||||||
std::vector<std::uint64_t> const& numbers
|
std::vector<std::uint64_t> const& numbers,
|
||||||
|
auto... ops
|
||||||
) -> bool
|
) -> bool
|
||||||
{
|
{
|
||||||
if (numbers.empty()) { return false; }
|
if (numbers.empty()) { return false; }
|
||||||
@ -45,13 +53,11 @@ auto calibrated(
|
|||||||
if (i == 0) {
|
if (i == 0) {
|
||||||
if (x == t) { return true; }
|
if (x == t) { return true; }
|
||||||
} else {
|
} else {
|
||||||
if (x < t) { work.emplace(i - 1, t - x); }
|
([&](auto const op) {
|
||||||
if (t % x == 0) { work.emplace(i - 1, t / x); }
|
if (auto const u = op(t, x)) {
|
||||||
if (part2) {
|
|
||||||
if (auto const u = drop_suffix(t, x)) {
|
|
||||||
work.emplace(i - 1, *u);
|
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;
|
std::uint64_t p1 = 0, p2 = 0;
|
||||||
for (auto && [x, xs] : input) {
|
for (auto && [x, xs] : input) {
|
||||||
if (calibrated(false, x, xs)) p1 += x;
|
if (calibrated(x, xs, try_subtract, try_divide)) p1 += x;
|
||||||
if (calibrated(true, x, xs)) p2 += x;
|
if (calibrated(x, xs, try_subtract, try_divide, try_unsuffix)) p2 += x;
|
||||||
}
|
}
|
||||||
|
|
||||||
out << "Part 1: " << p1 << "\n"
|
out << "Part 1: " << p1 << "\n"
|
||||||
|
Loading…
Reference in New Issue
Block a user