// Run an amplifier series in feedback mode for all possible phase settings, get the best result. public string PartTwo(string[] lines) { var source = new CPU(lines[0]); const int permutations = 120; return(Enumerable.Range(0, permutations).Max(seed => new AmplifierSeries(source, seed, true).RunAll()).ToString()); }
// Takes a "model" amplifier, which is copied to create instances, a "seed" (a number between 0 inclusive and // 120 exclusive) which describes the phase settings, and a switch that, if true, links up the final amplifier // back with the first one (as well as adjusting the final phase settings to use feedback mode). public AmplifierSeries(CPU amplifierModel, int seed, bool withFeedback = false) { amplifiers = Enumerable.Repeat(0, 5).Select(_ => new Computer.V3(amplifierModel)).ToArray(); for (int i = 0; i < 4; i++) { amplifiers[i].OutputTo(amplifiers[i + 1]); } if (withFeedback) { amplifiers[4].OutputTo(amplifiers[0]); } var phaseSettings = PermutationFromIndex(seed); for (int i = 0; i < 5; i++) { amplifiers[i].Input.Enqueue(phaseSettings[i] + (withFeedback ? 5 : 0)); } amplifiers[0].Input.Enqueue(0); }