From d6727ab770263ccad37f6b97498eb4acce3224ac Mon Sep 17 00:00:00 2001 From: Eric Mertens Date: Sat, 5 Nov 2022 15:40:30 -0700 Subject: [PATCH] advance --- day23.cpp | 19 ++++++++----------- lib/include/intcode/Interpreter.hpp | 28 ++++++++++++++++------------ 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/day23.cpp b/day23.cpp index 73e180d..01fd7f2 100644 --- a/day23.cpp +++ b/day23.cpp @@ -25,28 +25,25 @@ auto BuildNetwork(Machine m) -> std::vector { } auto Interact(Ethernet & ethernet, Machine & m, std::optional p) -> void { - while(std::visit(overloaded{ - - [&](Input i) { + while(Advance(m, + [&](auto &i) { if (p) { - i.pos = p->first; + i = p->first; StepInput(m, p->second); p = {}; return true; } - i.pos = -1; // no packet + i = -1; // no packet return false; }, - - [&](Output o) { + [&](auto d) { auto x = StepOutput(m); auto y = StepOutput(m); - ethernet.push_back({o.val, {x,y}}); + ethernet.push_back({d, {x,y}}); return true; }, - - [](Halt) -> bool { throw std::runtime_error{"unexpected halt"}; }, - }, Step(m))) {} + []() -> bool { throw std::runtime_error{"unexpected halt"}; } + )) {} } } // namespace diff --git a/lib/include/intcode/Interpreter.hpp b/lib/include/intcode/Interpreter.hpp index 13bc499..2fe2fdd 100644 --- a/lib/include/intcode/Interpreter.hpp +++ b/lib/include/intcode/Interpreter.hpp @@ -2,6 +2,7 @@ #define INTCODE_INTERPRETER_HPP_ #include +#include #include #include @@ -27,19 +28,22 @@ struct BadInstruction : public std::runtime_error { explicit BadInstruction(char const* what); }; -template +template Fin, std::invocable Fout, std::invocable<> Fhalt> +auto Advance(Machine & machine, Fin input, Fout output, Fhalt halt) { + return std::visit(overloaded{ + [&](Halt) { return halt(); }, + [&](Input i) { return input(i.pos); }, + [&](Output o) { return output(o.val); }, + }, Step(machine)); +} + +template Fin, std::invocable Fout> auto Run(Machine & machine, Fin input, Fout output) -> void { - while (std::visit(overloaded{ - [](Halt) { return false; }, - [&](Input arg) { - arg.pos = input(); - return true; - }, - [&](Output arg) { - output(arg.val); - return true; - }}, - Step(machine))); + while (Advance(machine, + [&](ValueType &i) { i = input(); return true; }, + [&](ValueType o) { output(o); return true; }, + []() { return false; } + )) {} } } // namespace