This commit is contained in:
Eric Mertens 2022-11-05 15:40:30 -07:00
parent d96eafaa47
commit d6727ab770
2 changed files with 24 additions and 23 deletions

View File

@ -25,28 +25,25 @@ auto BuildNetwork(Machine m) -> std::vector<Machine> {
}
auto Interact(Ethernet & ethernet, Machine & m, std::optional<Packet> 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

View File

@ -2,6 +2,7 @@
#define INTCODE_INTERPRETER_HPP_
#include <variant>
#include <concepts>
#include <intcode/Machine.hpp>
#include <Overload.hpp>
@ -27,19 +28,22 @@ struct BadInstruction : public std::runtime_error {
explicit BadInstruction(char const* what);
};
template <class Fin, class Fout>
template <std::invocable<ValueType&> Fin, std::invocable<ValueType> 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 <std::invocable<> Fin, std::invocable<ValueType> 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