From df4c18e47be4bef977e311bb427698b72d48b197 Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Tue, 4 Apr 2023 21:11:22 -0700 Subject: [PATCH] 21 working --- 2022/21.cpp | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/2022/21.cpp b/2022/21.cpp index 70a584a..54300a0 100644 --- a/2022/21.cpp +++ b/2022/21.cpp @@ -7,7 +7,6 @@ #include #include -#include #include #include @@ -85,10 +84,10 @@ auto Parse(std::istream & in) -> Input } auto Eval( - std::unordered_map & values, + std::unordered_map & values, std::unordered_map const& exprs, std::string const& var) - -> std::int64_t + -> double { auto it = values.find(var); if (it != values.end()) { @@ -97,7 +96,7 @@ auto Eval( auto const& [lhs,rhs,op] = exprs.at(var); auto const l = Eval(values, exprs, lhs); auto const r = Eval(values, exprs, rhs); - std::int64_t o; + double o; switch (op) { case Op::Add: o = l + r; break; case Op::Sub: o = l - r; break; @@ -110,7 +109,7 @@ auto Eval( auto Part1(Input const& input) -> std::int64_t { - std::unordered_map values; + std::unordered_map values; std::unordered_map exprs; for (auto const& entry : input) { std::visit(overloaded { @@ -123,7 +122,7 @@ auto Part1(Input const& input) -> std::int64_t auto Part2(Input const& input) -> std::int64_t { - std::unordered_map values; + std::unordered_map values; std::unordered_map exprs; for (auto const& entry : input) { std::visit(overloaded { @@ -134,26 +133,24 @@ auto Part2(Input const& input) -> std::int64_t exprs.at("root").op = Op::Sub; - auto eval = [&](std::int64_t humn) -> std::int64_t { + auto eval = [&](double humn) -> double { auto values_ = values; values_.at("humn") = humn; return Eval(values_, exprs, "root"); }; - auto x0 = 10; - auto x1 = 20; + auto x0 = 10.0; + auto x1 = 20.0; auto fx0 = eval(x0); - auto fx1 = eval(x1); - std::int64_t a = 0, b = 1; - while (x0 != x1 || a%b != 0) { - a = eval(x1) * (x1 - x0); - b = eval(x1) - eval(x0); - auto const x2 = x1 - a / b; + while (std::abs(x0 - x1) > 0.01) { + auto const fx1 = eval(x1); + auto const x2 = x1 - fx1 * (x1 - x0) / (fx1 - fx0); x0 = x1; x1 = x2; + fx0 = fx1; } - return x0; + return std::round(x1); } } // namespace