aocpp/day07.cpp

67 lines
1.7 KiB
C++
Raw Normal View History

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>
2022-11-04 09:38:01 -07:00
#include <intcode/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 14:43:47 -07:00
template <class R> auto Controller(Machine machine, R const &params) {
2022-11-03 12:53:10 -07:00
std::vector<Machine> amps;
for (auto p : params) {
auto m = machine;
2022-11-04 08:29:02 -07:00
std::get<Input>(Step(m)).pos = p;
2022-11-03 12:53:10 -07:00
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>
2022-11-03 14:43:47 -07:00
auto Feed(R &&amps, ValueType start) -> std::optional<ValueType> {
2022-11-03 12:53:10 -07:00
for (auto &m : amps) {
2022-11-04 08:29:02 -07:00
auto i = Step(m);
2022-11-03 12:53:10 -07:00
if (auto p = std::get_if<Input>(&i)) {
p->pos = start;
2022-11-04 08:29:02 -07:00
start = std::get<Output>(Step(m)).val;
2022-11-03 12:53:10 -07:00
} 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 14:43:47 -07:00
auto compute1(Machine machine, std::vector<ValueType> const &params)
-> ValueType {
return *Feed(Controller(std::move(machine), params), 0);
2022-11-03 08:15:17 -07:00
}
2022-11-03 14:43:47 -07:00
auto compute2(Machine machine, std::vector<ValueType> const &params)
-> ValueType {
auto amps = Controller(std::move(machine), params);
ValueType last = 0;
while (auto next = Feed(amps, last)) {
2022-11-03 12:53:10 -07:00
last = *next;
}
return last;
}
2022-11-03 14:43:47 -07:00
template <std::invocable<Machine, std::vector<ValueType> const &> F>
auto optimize(Machine machine, std::vector<ValueType> params, F f) {
ValueType best = 0;
2022-11-03 12:53:10 -07:00
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 14:43:47 -07:00
auto machine = Machine{ParseStream(std::cin)};
2022-11-03 12:53:10 -07:00
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;
}