aocpp/intcode/src/Interpreter.cpp

86 lines
1.6 KiB
C++
Raw Normal View History

2022-11-04 09:38:01 -07:00
#include <intcode/Interpreter.hpp>
2022-11-03 08:15:17 -07:00
2022-11-03 12:53:10 -07:00
namespace intcode {
2022-11-07 17:19:17 -08:00
BadInstruction::BadInstruction(char const* const what)
2022-11-03 14:43:47 -07:00
: std::runtime_error{what} {}
2022-11-03 12:53:10 -07:00
2022-11-07 17:19:17 -08:00
auto StepInput(Machine & m, ValueType const input) -> void {
2022-11-06 19:46:43 -08:00
std::get<Input>(Step(m)).input = input;
2022-11-05 15:06:54 -07:00
}
auto StepOutput(Machine & m) -> ValueType {
2022-11-06 19:46:43 -08:00
return std::get<Output>(Step(m)).output;
2022-11-05 15:06:54 -07:00
}
2022-11-04 08:29:02 -07:00
auto Step(Machine & m) -> std::variant<Input, Output, Halt> {
2022-11-03 12:53:10 -07:00
for (;;) {
2022-11-07 17:19:17 -08:00
auto next = m.Next();
auto const instruction = next % 100; next /= 100;
2022-11-04 08:29:02 -07:00
2022-11-07 17:19:17 -08:00
auto const arg = [&]() -> ValueType & {
2022-11-04 08:29:02 -07:00
auto &v = m.Next();
2022-11-07 17:19:17 -08:00
auto const mode = next % 10; next /= 10;
switch (mode) {
case 0: return m.At(v);
case 1: return v;
case 2: return m.Rel(v);
default: throw BadInstruction{"invalid addressing mode"};
2022-11-04 08:29:02 -07:00
}
};
2022-11-03 12:53:10 -07:00
2022-11-07 17:19:17 -08:00
switch (instruction) {
case 1:
2022-11-04 21:27:08 -07:00
arg() = arg() + arg();
2022-11-03 12:53:10 -07:00
break;
2022-11-07 17:19:17 -08:00
case 2:
2022-11-04 21:27:08 -07:00
arg() = arg() * arg();
2022-11-03 12:53:10 -07:00
break;
2022-11-07 17:19:17 -08:00
case 3:
2022-11-04 08:29:02 -07:00
return Input{arg()};
2022-11-03 12:53:10 -07:00
2022-11-07 17:19:17 -08:00
case 4:
2022-11-04 08:29:02 -07:00
return Output{arg()};
2022-11-03 12:53:10 -07:00
2022-11-04 08:29:02 -07:00
case 5: {
2022-11-07 17:19:17 -08:00
auto const a = arg();
auto const b = arg();
2022-11-04 08:29:02 -07:00
if (a) { m.Goto(b); }
2022-11-03 12:53:10 -07:00
break;
2022-11-04 08:29:02 -07:00
}
2022-11-03 12:53:10 -07:00
2022-11-04 08:29:02 -07:00
case 6: {
2022-11-07 17:19:17 -08:00
auto const a = arg();
auto const b = arg();
2022-11-04 08:29:02 -07:00
if (!a) { m.Goto(b); }
2022-11-03 12:53:10 -07:00
break;
2022-11-04 08:29:02 -07:00
}
2022-11-03 12:53:10 -07:00
2022-11-04 08:29:02 -07:00
case 7: {
2022-11-07 17:19:17 -08:00
auto const a = arg();
arg() = a < arg();
2022-11-03 12:53:10 -07:00
break;
2022-11-04 08:29:02 -07:00
}
2022-11-03 12:53:10 -07:00
2022-11-07 17:19:17 -08:00
case 8:
2022-11-04 21:27:08 -07:00
arg() = arg() == arg();
2022-11-03 12:53:10 -07:00
break;
case 9:
2022-11-04 08:29:02 -07:00
m.Rebase(arg());
2022-11-03 12:53:10 -07:00
break;
case 99:
return Halt{};
default:
2022-11-07 17:19:17 -08:00
std::cout << instruction << std::endl;
2022-11-03 14:43:47 -07:00
throw BadInstruction{"invalid opcode"};
2022-11-03 12:53:10 -07:00
}
}
}
2022-11-04 09:38:01 -07:00
} // namespace