Based on the navigational maps, you're going to need to send more power to your ship's thrusters to reach Santa in time. To do this, you'll need to configure a series of amplifiers already installed on the ship.
There are five amplifiers connected in series; each one receives an input signal and produces an output signal. They are connected such that the first amplifier's output leads to the second amplifier's input, the second amplifier's output leads to the third amplifier's input, and so on. The first amplifier's input value is 0
, and the last amplifier's output leads to your ship's thrusters.
Read the full puzzle.
using System;
using System.Collections.Generic;
using System.Linq;
namespace AdventOfCode.Y2019.Day07;
[ProblemName("Amplification Circuit")]
class Solution : Solver {
public object PartOne(string prg) => Solve(prg, false, new[] { 0, 1, 2, 3, 4 });
public object PartTwo(string prg) => Solve(prg, true, new[] { 5, 6, 7, 8, 9 });
long Solve(string prg, bool loop, int[] prgids) {
var amps = Enumerable.Range(0, 5).Select(x => new IntCodeMachine(prg)).ToArray();
var max = 0L;
foreach (var perm in Permutations(prgids)) {
max = Math.Max(max, ExecAmps(amps, perm, loop));
}
return max;
}
long ExecAmps(IntCodeMachine[] amps, int[] prgid, bool loop) {
for (var i = 0; i < amps.Length; i++) {
amps[i].Reset();
amps[i].input.Enqueue(prgid[i]);
}
var data = new[] { 0L };
while (true) {
for (var i = 0; i < amps.Length; i++) {
data = amps[i].Run(data).ToArray();
}
if (amps.All(amp => amp.Halted())) {
return data.Last();
}
if (!loop) {
data = new long[0];
}
}
}
IEnumerable<T[]> Permutations<T>(T[] rgt) {
IEnumerable<T[]> PermutationsRec(int i) {
if (i == rgt.Length) {
yield return rgt.ToArray();
}
for (var j = i; j < rgt.Length; j++) {
(rgt[i], rgt[j]) = (rgt[j], rgt[i]);
foreach (var perm in PermutationsRec(i + 1)) {
yield return perm;
}
(rgt[i], rgt[j]) = (rgt[j], rgt[i]);
}
}
return PermutationsRec(0);
}
}
Please ☆ my repo if you like it!