def part1(): real = list(eval(open('day13.txt').read())) pgm = Program(real) pgm.run() queue = pgm.dump() print(len(queue)) twos = [1 for k in take(queue, 3) if k[2] == 2] print("Part 1:", len(twos)) # 228
def test_corners(program: Program, x: int, y: int) -> bool: for xx, yy in [(x, y), (x + 99, y), (x, y + 99), (x + 99, y + 99)]: program.reset() program.add_input(xx) program.add_input(yy) if next(program.operate()) != 1: return False return True
def find_noun_verb(data, target): for noun, verb in itertools.product(range(100), repeat=2): prog = Program(data) prog[1] = noun prog[2] = verb prog.execute() if prog[0] == target: return (noun, verb) return None
def scan(program: Program, shape: Tuple[int, int] = (50, 50)) -> np.array: grid = np.zeros(shape, dtype=int) for x in range(shape[0]): for y in range(shape[1]): program.add_input(x) program.add_input(y) grid[x][y] = next(program.operate()) program.reset() return grid
def get_field(data): result = {} p = Program(data, [], pause_on_output=True) while not p.halted: p.outputs.clear() p.run_times(3) if not p.halted: x, y, tile = p.outputs result[(x, y)] = tile return result
def find_highest_output(prog_input): highest = 0 for phases in permutations(range(5), 5): last_out = 0 for phase in phases: prog = Program(prog_input, [phase, last_out]) prog.execute() last_out = prog.output_values[0] highest = max(highest, last_out) return highest
def main(): prog_data = parse_program_input(sys.stdin.read().strip()) prog = Program(prog_data) robot = PaintRobot(prog) robot.run() print("Number of panels painted:", len(robot.panels)) prog = Program(prog_data) robot = PaintRobot(prog) robot.paint(WHITE_N) robot.run() draw_grid(robot.panels)
def main(): data = parse_program_input(sys.stdin.read()) program = Program(data) program[1] = 12 program[2] = 2 program.execute() print("Part 1", program[0]) target = 19690720 noun, verb = find_noun_verb(data, target) print("Part 2", 100 * noun + verb)
def in_tractor(x, y, _cache={}): pos = (x, y) result = _cache.get(pos) if result is not None: return result prog = Program(prog_input) prog.input_values = [x, y] prog.execute() result = bool(prog.output_values[-1]) _cache[pos] = result return result
def main(): prog_input = parse_program_input(sys.stdin.read().strip()) prog = Program(prog_input) prog.execute() view = prog.output_values view = ''.join(map(chr, view)).strip() print(view) viewlines = view.splitlines() alignment = sum(x*y for (x,y) in intersections(viewlines, SCAFFOLD_S)) print("Alignment:", alignment) grid = LineGrid(viewlines) print("Route:") print(','.join(t+str(s) for (t,s) in find_path(grid))) # I didn't find this programmatically, just from inspection patternA = 'L,12,L,12,R,12' patternB = 'L,8,L,8,R,12,L,8,L,8' patternC = 'L,10,R,8,R,12' route = 'A,A,B,C,C,A,B,C,A,B' feed = 'n\n' input_string = '\n'.join([route, patternA, patternB, patternC, feed]) prog_data = list(prog_input) prog_data[0] = 2 prog = Program(prog_data) prog.run_input(input_string) print(''.join(chr(v) if v < 256 else '\n%s'%v for v in prog.output_values))
def part2(): program = Program("17") program.program[0] = 2 main = "A,B,A,B,C,B,C,A,B,C\n" a = "R,4,R,10,R,8,R,4\n" b = "R,10,R,6,R,4\n" c = "R,4,L,12,R,6,L,12\n" camera = "n\n" input_buffer = [] [input_buffer.extend(ord(c) for c in routine) for routine in [main, a, b, c, camera]] program.run(input_buffer) return program.output_buffer[-1]
def run_robot(data, start_with_white): p = Program(data, [], pause_on_output=True) r = Robot() if start_with_white: r.painted[0j] = 1 while True: p.inputs = [r.get_camera()] p.outputs.clear() p.run_times(2) if p.halted: break color, turn = p.outputs r.step(color, turn) return r
def explore(program: Program) -> Grid: program.reset() available_moves: DefaultDict[complex, List[int]] = defaultdict(lambda: [4, 2, 3, 1]) backtracking: List[int] = list() grid: Grid = dict() position = 0j available_moves[position] # init to enter the loop while any(available_moves.values()) or backtracking: if available_moves[position]: direction = available_moves[position].pop() program.add_input(direction) status = next(program.operate()) grid[position + moves[direction]] = status if status in [1, 2]: backtracking.append(back[direction]) position += moves[direction] else: # We hit a wall, don't move continue else: # no move available, backtrack direction = backtracking.pop() program.add_input(direction) next(program.operate()) # we know it will be 1 position += moves[direction] return grid
def main(): data = parse_program_input(sys.stdin.read()) prog = Program(data, [1]) prog.execute() print(prog.output_values) prog = Program(data, [2]) prog.execute() print(prog.output_values)
def main(): data = parse_program_input(sys.stdin.read()) prog = Program(data, [1]) prog.execute() print("First program output:", prog.output_values[-1]) prog = Program(data, [5]) prog.execute() print("Second program output:", prog.output_values[-1])
def feedback_loop(program, modes, input): program_copies = [] outputs = [] output = input for i in range(0, 5): program_copies.append(Program(program.copy())) output = amplifier(program_copies[i], output, modes[i]) outputs.append(output) i = 0 halts = 0 while True: output = amplifier(program_copies[i], output) if output is not None: outputs[i] = output else: halts += 1 if halts == 5: break i += 1 if i == 5: i = 0 halts = 0 return outputs[4]
def create_programs(program_input, queues, nat=None): programs = [Program(program_input) for _ in range(50)] for i,prog in enumerate(programs): prog.queue = queues[i] prog.queue.append(i) prog.awaiting = False def prog_input(p=prog): if not p.queue: p.awaiting = True return -1 return p.queue.pop(0) prog.input_func = prog_input def prog_output(value, oc=[]): oc.append(value) if len(oc)==3: prog.awaiting = False destination, x, y = oc oc.clear() q = queues[destination] if destination < len(programs): programs[destination].awaiting = False if destination==nat: q[:] = [x,y] else: q += [x,y] prog.output_func = prog_output return programs
def calc_phase_setting(initial_memory: List[int], sequence: Iterable[int]) -> int: phase_setting = 0 programs: List[Program] = [] halted = False while not halted: for i, program_input in enumerate(sequence): if len(programs) <= i: programs.append(Program(initial_memory)) # Run with program_input only first time _, outputs = run(programs[i], inputs=[program_input, phase_setting]) else: # Already added -> has run at least once already _, outputs = run(programs[i], inputs=[phase_setting]) assert len(outputs) > 0 phase_setting = outputs[-1] halted = programs[i].memory[programs[i].memory_ptr] == 99 if halted: programs[i].memory_ptr = 0 return phase_setting
def get_ascii(program: Program) -> str: grid = [] while True: try: grid.append(chr(next(program.operate()))) except StopIteration: break return "".join(grid)
def runsequence( pgm0 ): maxval = 0 for ip in itertools.permutations([5,6,7,8,9]): if TRACE: print( ip ) amps = [ Program(pgm0), Program(pgm0), Program(pgm0), Program(pgm0), Program(pgm0) ] # The output from 0 becomes the input to 1. q = amps[4].output for amp in amps: amp.input = q q = amp.output # Set the initial input for each amp. for amp,val in zip(amps,ip): amp.input.put( val ) # Set the first signal into amp 0. amps[0].push( 0 ) # Go. for amp in amps: amp.start() # Wait for all to exit. for amp in amps: amp.join() # The answer is waiting in amp 4's output queue. maxval = max( maxval, amps[4].pop() ) return maxval
def check_in_beam(pdata, xpos, ypos): p = Program(copy.copy(pdata)) p.eval() assert (p.waitingForInput()) p.pushInput(xpos) p.pushInput(ypos) output = p.eval() assert (len(output) == 1) return output[0] == 1
def runsequence( pgm0 ): maxval = 0 for inputset in itertools.permutations((0,1,2,3,4)): print( inputset ) lastval = 0 for ip in inputset: lastval = Program(pgm0, [ip, lastval]).run().dump()[0] print( lastval ) maxval = max(maxval,lastval) return maxval
def test_sample(): programs = ( [3, 0, 4, 0, 99], [1101, 100, -1, 4, 0], [3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], [3, 3, 1108, -1, 8, 3, 4, 3, 99], [3, 3, 1107, -1, 8, 3, 4, 3, 99], [ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ], ) for prog in programs: p = Program(prog, [9]) p.run() print(p.outputs) exit(0)
def part2(): real = list(eval(open('day13.txt').read())) # Make one run to determine the limits of the grid. pgm = Program(real) pgm.run() queue = list(take(pgm.dump(), 3)) w = max(k[0] for k in queue) + 1 h = max(k[1] for k in queue) + 1 print(w, h) # Create the printable grid. grid = [] for i in range(h): grid.append([' '] * w) # Populate it from the part 1 output. for x, y, t in queue: grid[y][x] = ' #x-o'[t] display(grid) # Insert a quarter. real[0] = 2 # Go run the app. pgm = Prog13(real) pgm.grid = grid pgm.run() # Pop any unfinished output. pgm.clear_queue() display(grid) print("Part 2:", pgm.score) # 10776
def test_sample(): test_programs = [ [1, 0, 0, 0, 99], [2, 3, 0, 3, 99], [2, 4, 4, 5, 99, 0], [1, 1, 1, 4, 99, 5, 6, 0, 99], ] for prog in test_programs: print('BEFORE', prog) Program(prog, []).run() print('AFTER', prog)
def part1(): program = Program("17") program.run() x, y = (0, 0) scaffold = [] for c in program.output_buffer: print(chr(c), end='') if chr(c) == "\n": y += 1 x = 0 continue elif chr(c) in ["#", "^", "v", "<", ">"]: scaffold.append((x, y)) x += 1 intersections = [(x, y) for (x, y) in scaffold if (all(neighbour in scaffold for neighbour in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]))] return sum([(x * y) for (x, y) in intersections])
def main(): prog_input = parse_program_input(sys.stdin.read().strip()) program = Program(prog_input) game = Director(program) try: game.play() except StopIteration as e: print(e) game.render() print("Distance to target:", game.steps[game.target]) game.flood_steps(game.target) print("Time to fill with oxygen:", max(game.steps.values()))
def run_feedback(prog_input): highest = 0 for phases in permutations(range(5, 10), 5): progs = [Program(prog_input, [phase]) for phase in phases] last_output = 0 while progs[-1].pos >= 0: for prog in progs: prog.input_values.append(last_output) prog.execute_till_output() last_output = prog.output_values[-1] highest = max(highest, last_output) return highest
def run_with_queues(instructions, readQ, writeQ): def read(): while True: try: x = readQ.get_nowait() yield x break except queue.Empty: yield None def write(x): writeQ.put_nowait(x) return Program(instructions, read, write)
def part2(): pgm = Program(real) pgm.pgm[0] = 2 instructions = ( "A,B,A,C,C,A,B,C,B,B\n", "L,8,R,10,L,8,R,8\n", "L,12,R,8,R,8\n", "L,8,R,6,R,6,R,10,L,8\n", "n\n" ) for c in ''.join(instructions): pgm.push(ord(c)) pgm.run() d = pgm.dump() if TRACE: print( Maze(d[:-1]).string ) return d[-1]