Exemplo n.º 1
0
class Day7:
    def __init__(self, program, namps=5, debug=0):
        #self.amps = []
        self.namps = namps
        self.debug = debug
        self.amp = Intcode(program, debug)
        #for _ in range(namps):
        #    self.amps.append(Intcode(program, debug=debug))

    @classmethod
    def from_file(cls, filename, namps=5, debug=0):
        program = ""
        with open(filename, "r") as fh:
            for l in fh:
                program += l.rstrip()
        return cls(program, namps, debug)

    def run_amps(self, phase_setting):
        inp = 0
        for i in range(self.namps):
            out = self.amp.run(inp=[phase_setting[i], inp])
            #print(out)
            inp = out[0]
        return (inp)

    def run_amps_feedback(self, phase_setting):
        # create an IntcodeProcess for each amp and set first input
        # of each to phase_setting[i]
        amp_process = []
        for i in range(self.namps):
            amp_process.append(self.amp.create_process(inp=[phase_setting[i]]))

        inp = 0
        outall = []
        while True:
            for i in range(self.namps):
                amp_process[i].set_input(inp)
                out = amp_process[i].run_to_next_output()
                #print(out)
                if out != None:
                    outall.append(out)
                if amp_process[i].is_terminated():
                    print(outall)
                    return outall[-1]
                inp = out

    def run_all(self, permute=[0, 1, 2, 3, 4], method=None):
        if method == None:
            method = self.run_amps
        best_settings, best_output = "", 0
        for s in itertools.permutations(permute):
            output = method(s)
            settings = "".join([str(si) for si in s])
            if output > best_output:
                best_settings, best_output = settings, output
        return best_settings, best_output
Exemplo n.º 2
0
 def __init__(self, nic_code: Intcode, addr: int):
     self.addr = addr
     self.nic = nic_code.create_process()
     self.nic.set_input(addr)
     self.queue = deque()
     self.n_empty_input = 0