aocpp/day23.cpp
2022-11-05 21:48:52 -07:00

83 lines
1.8 KiB
C++

#include <cstddef>
#include <deque>
#include <iostream>
#include <stdexcept>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>
#include <intcode/intcode.hpp>
using namespace intcode;
namespace {
using Packet = std::pair<ValueType, ValueType>;
using Ethernet = std::deque<std::pair<std::size_t, Packet>>;
auto BuildNetwork(Machine m) -> std::vector<Machine> {
auto& i = std::get<Input>(Step(m)).pos;
std::vector<Machine> machines;
for (i = 0; i < 50; i++) {
machines.push_back(m);
}
return machines;
}
auto Interact(Ethernet & ethernet, Machine & m, std::optional<Packet> p) -> void {
while(Advance(m,
[&](auto &i) {
if (p) {
i = p->first;
StepInput(m, p->second);
p = {};
return true;
}
i = -1; // no packet
return false;
},
[&](auto d) {
auto x = StepOutput(m);
auto y = StepOutput(m);
ethernet.push_back({d, {x,y}});
return true;
},
[]() -> bool { throw std::runtime_error{"unexpected halt"}; }
)) {}
}
} // namespace
auto main() -> int {
auto machines = BuildNetwork(Machine{ParseStream(std::cin)});
auto ethernet = Ethernet{};
std::optional<ValueType> part1;
std::optional<ValueType> part2;
std::optional<Packet> nat;
for(;;) {
if (!ethernet.empty()) {
auto [dest, p] = ethernet.front();
ethernet.pop_front();
if (dest == 255) {
nat = p;
if (!part1) { part1 = p.second; }
} else {
Interact(ethernet, machines.at(dest), p);
}
} else if (nat) {
if (nat->second == part2) { break; }
part2 = nat->second;
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;
}