aocpp/day23.cpp
2022-11-06 11:33:20 -08:00

89 lines
2.0 KiB
C++

#include <cstddef>
#include <deque>
#include <iostream>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>
#include <fstream>
#include <intcode/intcode.hpp>
using namespace intcode;
namespace {
struct Payload { ValueType x, y; };
struct Packet { ValueType destination; Payload payload; };
using Ethernet = std::deque<Packet>;
auto BuildNetwork(Machine m) -> std::vector<Machine> {
std::vector<Machine> machines;
auto& i = std::get<Input>(Step(m)).pos;
for (i = 0; i < 50; i++) {
machines.push_back(m);
}
return machines;
}
auto Interact(Ethernet & ethernet, Machine & m, std::optional<Payload> p) -> void {
for(;;) {
auto e = Step(m);
switch (e.index()) {
default: throw std::runtime_error{"unexpected halt"};
case 0: {
auto& i = std::get<0>(e).pos;
if (p) {
i = p->x;
StepInput(m, p->y);
p = {};
break;
}
i = -1; // no packet
return;
}
case 1: {
auto d = std::get<1>(e).val;
auto x = StepOutput(m);
auto y = StepOutput(m);
ethernet.push_back({d, {x,y}});
}
}
}
}
} // namespace
auto main(int argc, char** argv) -> int {
auto machines = BuildNetwork(Startup(argc, argv));
auto ethernet = Ethernet{};
std::optional<ValueType> part1;
std::optional<ValueType> part2;
std::optional<Payload> nat;
for(;;) {
if (!ethernet.empty()) {
auto packet = ethernet.front();
ethernet.pop_front();
if (packet.destination == 255) {
nat = packet.payload;
if (!part1) { part1 = packet.payload.y; }
} else {
Interact(ethernet, machines.at(packet.destination), packet.payload);
}
} else if (nat) {
if (part2 == nat->y) { break; }
part2 = nat->y;
Interact(ethernet, machines[0], nat);
} else {
for (auto & m : machines) {
Interact(ethernet, m, {});
}
}
}
std::cout << "Part 1: " << *part1 << std::endl;
std::cout << "Part 2: " << *part2 << std::endl;
}