2022-11-03 12:53:10 -07:00
|
|
|
#include <algorithm>
|
|
|
|
#include <concepts>
|
2022-11-03 08:15:17 -07:00
|
|
|
#include <iostream>
|
2022-11-03 12:53:10 -07:00
|
|
|
#include <optional>
|
2022-11-03 08:15:17 -07:00
|
|
|
#include <utility>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
#include <intcode.hpp>
|
2022-11-03 12:53:10 -07:00
|
|
|
using namespace intcode;
|
2022-11-03 08:15:17 -07:00
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
2022-11-03 12:53:10 -07:00
|
|
|
template <class R> auto set_params(Machine machine, R const ¶ms) {
|
|
|
|
std::vector<Machine> amps;
|
|
|
|
for (auto p : params) {
|
|
|
|
auto m = machine;
|
|
|
|
std::get<Input>(m.step()).pos = p;
|
|
|
|
amps.push_back(std::move(m));
|
|
|
|
}
|
|
|
|
return amps;
|
2022-11-03 08:15:17 -07:00
|
|
|
}
|
|
|
|
|
2022-11-03 12:53:10 -07:00
|
|
|
template <class R>
|
|
|
|
auto feed(R &&s, value_type start) -> std::optional<value_type> {
|
|
|
|
for (auto &m : amps) {
|
|
|
|
auto i = m.step();
|
|
|
|
if (auto p = std::get_if<Input>(&i)) {
|
|
|
|
p->pos = start;
|
|
|
|
start = std::get<Output>(m.step()).val;
|
|
|
|
} else {
|
|
|
|
return {};
|
2022-11-03 08:15:17 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
}
|
|
|
|
return {start};
|
|
|
|
}
|
2022-11-03 08:15:17 -07:00
|
|
|
|
2022-11-03 12:53:10 -07:00
|
|
|
auto compute1(Machine machine, std::vector<value_type> const ¶ms)
|
|
|
|
-> value_type {
|
|
|
|
return *feed(set_params(std::move(machine), params), 0);
|
2022-11-03 08:15:17 -07:00
|
|
|
}
|
2022-11-03 12:53:10 -07:00
|
|
|
auto compute2(Machine machine, std::vector<value_type> const ¶ms)
|
|
|
|
-> value_type {
|
|
|
|
auto amps = set_params(std::move(machine), params);
|
|
|
|
value_type last = 0;
|
|
|
|
while (auto next = feed(amps, last)) {
|
|
|
|
last = *next;
|
|
|
|
}
|
|
|
|
return last;
|
|
|
|
}
|
|
|
|
|
|
|
|
template <std::invocable<Machine, std::vector<value_type> const &> F>
|
|
|
|
auto optimize(Machine machine, std::vector<value_type> params, F f) {
|
|
|
|
value_type best = 0;
|
|
|
|
do {
|
|
|
|
best = std::max(best, f(machine, params));
|
|
|
|
} while (std::next_permutation(params.begin(), params.end()));
|
|
|
|
return best;
|
2022-11-03 08:15:17 -07:00
|
|
|
}
|
|
|
|
|
2022-11-03 12:53:10 -07:00
|
|
|
} // namespace
|
|
|
|
|
2022-11-03 08:15:17 -07:00
|
|
|
auto main() -> int {
|
2022-11-03 12:53:10 -07:00
|
|
|
auto machine = Machine{parse_stream(std::cin)};
|
|
|
|
std::cout << "Part 1: " << optimize(machine, {0, 1, 2, 3, 4}, compute1) << std::endl;
|
|
|
|
std::cout << "Part 2: " << optimize(std::move(machine), {5, 6, 7, 8, 9}, compute2) << std::endl;
|
|
|
|
}
|