day 07
amplification circuit
approach
the day 5 interpreter is copied in, with one change: input is a list that opcode 3 pops from. part 1 tries every permutation of phases 0–4. for each, it runs the five amplifiers in a row, each on a fresh copy of the program with its phase and the previous amplifier's output, and keeps the highest final signal.
part 2 wires the amplifiers into a loop. feedback_loop creates five generators up front, each with its own input list holding its phase (the first one also gets 0). it then cycles through them, takes one output from each and appends it to the next amplifier's input list. when an amplifier halts, the last value passed along is the answer. a commented-out earlier attempt at part 2 is still at the bottom of the file.
the trick
paused generators sharing input lists are all the concurrency the feedback loop needs.
def feedback_loop(ic,p):
phases=[[x] for x in p]
phases[0].append(0)
amplifiers=[exec(ic[:],inpts) for inpts in phases]
while True:
for i,a in enumerate(amplifiers):
try:
x=next(a)
except StopIteration:
return x
phases[(i+1) % len(phases)].append(x)