def get_game(play_for_free=False): l = read_program("13.txt") # Memory address 0 represents the number of quarters that have been inserted; # set it to 2 to play for free. if play_for_free: l[0] = 2 return Intcode(l)
#!/usr/bin/env python3 from intcode import read_program, Computer if __name__ == '__main__': program = read_program('day05.txt') c = Computer(program) c.push_input(5) c.execute()
out = 0 for phase in phase_setting: out = list(Intcode(l, [phase, out]).run_program())[0] max_out = max(max_out, out) return max_out def max_signal2(l): max_out = float("-inf") for phase_setting in permutations(range(5, 10)): amplifiers = [Intcode(l, [phase_setting[i]]) for i in range(5)] out = 0 i = 0 while True: idx = i % len(amplifiers) amplifier = amplifiers[idx] amplifier.inputs.append(out) try: out = next(iter(amplifier)) except StopIteration: break i += 1 max_out = max(max_out, out) return max_out l = read_program("7.txt") print(max_signal(l)) print(max_signal2(l))
amps = [deepcopy(data) for _ in range(5)] for phase, amp in zip(phases, amps): amp[3].append(phase) resume(amp) amps[0][3].append(0) resume(amps[0]) while not amps[4][5]: for i, amp in enumerate(amps): amps[(i + 1) % 5][3].append(amp[4][-1]) resume(amps[(i + 1) % 5]) return amps[4][4][-1] if __name__ == "__main__": d = read_program("data/input07.data") part1 = max( run_amplifiers(d, phases) for phases in permutations(range(5)) ) print(f"Part1: {part1}") part2 = max( run_amplifiers(d, phases) for phases in permutations(range(5, 10)) ) print(f"Part2: {part2}")
for nic in nics: assert next(nic) is None while True: for nic, msg in zip(nics, messages): msg.append(-1) while msg: dst = nic.send(msg.pop(0)) while dst is not None: pack = next(nic), next(nic) if dst == 255: natpack = pack else: messages[dst].extend(pack) dst = next(nic) if not any(messages): messages[0].extend(natpack) yield natpack[1] def find_repeated_natpack(program): seen = set() for y in run_nat(program): if y in seen: return y seen.add(y) program = read_program(sys.stdin) print(next(run_nat(program))) print(find_repeated_natpack(program))
s = string_path.replace(valid[0], "A") \ .replace(valid[1], "B") \ .replace(valid[2], "C") main = list(s) A = encode(valid[0][:-1].split(",")) B = encode(valid[1][:-1].split(",")) C = encode(valid[2][:-1].split(",")) return encode(main) + A + B + C + [ord("n"), ord("\n")] raise Exception("No partition found") if __name__ == "__main__": code = read_program("data/input17.data") g, bot, heading = make_graph(code) xmax = max(n[0] for n in g) ymax = max(n[1] for n in g) intersects = find_intersections(g, xmax, ymax) print(f"Part1: {alignment(intersects)}") # Part 2 path = make_path(g, xmax, ymax, bot, heading) instr = partition(path) code = read_program("data/input17.data") poke(code, 0, 2) # wake the robot code[3] = instr resume(code)
# Easy way to escape recursion raise FoundOxygenException() self.grid[new_coord] = status if status != WALL_STATUS: self.travel(new_coord, steps=steps + 1, stop_at_oxygen=stop_at_oxygen) # Since this path is traversed, go back and keep exploring self.intcode.inputs.append( self.delta_to_dir[opposite_delta(delta)]) # Can't be a wall because we just came from here and the grid is not changing assert next(self.it) != WALL_STATUS traversal = Traversal(Intcode(read_program("15.txt"))) traversal.explore() if VISUALIZE: render_sparse_grid(traversal.grid, START_COORD) oxygen_coord = None for k, v in traversal.grid.items(): if v == OXYGEN_STATUS: oxygen_coord = k break print("1) Answer", traversal.min_steps[oxygen_coord]) # 280 # Reposition at the oxygen
#!/usr/bin/env python3 from intcode import read_program from amplifier import AmpSequence if __name__ == '__main__': program = read_program('day07.txt') settings, signal = AmpSequence.find_max_feedback_loop_settings(program) print(signal)
#!/usr/bin/env python3 from intcode import read_program, Computer program = read_program('day02.txt') program1202 = [program[0], 12, 2] + program[3:] c = Computer(program1202).execute() print(c.state[0])
# https://adventofcode.com/2019/day/9 from intcode import Intcode, read_program intcode = Intcode(read_program("9.txt"), [1]) out = intcode.program_output() assert len(out) == 1, out print("1) Answer:", out[0]) intcode = Intcode(read_program("9.txt"), [2]) out = intcode.program_output() assert len(out) == 1, out print("2) Answer:", out[0])
code[4] = [] resume(code) return code[4][0] def map_tractor_beam(c): affected = 0 for y in range(50): for x in range(50): affected += is_affected(c, x, y) return affected def fit_square(c, size): x = 0 for y in count(100): for dx in count(): if is_affected(c, x+dx, y): x += dx if is_affected(c, x + 99, y - 99): return (x, y - 99) break if __name__ == "__main__": code = read_program("data/input19.data") print(f"Part1: {map_tractor_beam(code)}") x, y = fit_square(code, 100) print(f"Part2: {x*10_000+y}")
def test_original_day02_program(): program = read_program('day02.txt') program1202 = [program[0],12,2] + program[3:] c = Computer(program1202) c.execute() assert c.state[0] == 4714701
dx, dy = 0, -1 for make_white in robot: painted.add((x, y)) (white.add if make_white else white.discard)((x, y)) dx, dy = (-dy, dx) if next(robot) else (dy, -dx) x += dx y += dy color = int((x, y) in white) return white, len(painted) def draw(coords): xmin = min(x for x, y in coords) xmax = max(x for x, y in coords) ymin = min(y for x, y in coords) ymax = max(y for x, y in coords) grid = [[0] * (xmax - xmin + 1) for y in range(ymin, ymax + 1)] for x, y in coords: grid[y - ymin][x - xmin] = 1 for row in grid: print(''.join(' @'[c] for c in row)) firmware = read_program(sys.stdin) white, npainted = paint(firmware, 0) print(npainted) white, npainted = paint(firmware, 1) draw(white)
grid, score = makegrid(game) xpaddle = xball = 0 if verbose: draw(grid, score) try: while True: x, y, ident = islice(game, 3) if x == -1: score = ident else: grid[y][x] = ident if ident == 3: xpaddle = x elif ident == 4: xball = x if verbose: draw(grid, score) sleep(.003) except (StopIteration, ValueError): return score # part 1 code = read_program(sys.stdin) outp = list(run_getter(code, lambda: 0)) print(outp[2::3].count(2)) # part 2 code[0] = 2 print(play(code, '-v' in sys.argv))
inventory.append(item) if loc == 'Pressure-Sensitive Floor': destination_path = tuple(path) if loc not in visited: visited.add(loc) for d in directions: if d != opposite_directions[direction]: dfs(loc, d, path + [d]) send_command(droid, opposite_directions[d]) inventory = [] destination_path = None visited = {'outside'} dfs('outside', '', []) for direction in destination_path[:-1]: send_command(droid, direction) for dropnum in range(len(inventory)): for dropitems in combinations(inventory, dropnum): for item in dropitems: send_command(droid, 'drop ' + item) output = send_command(droid, destination_path[-1]) if 'Alert!' not in output: return int(re.search(r'\d+', output).group(0)) for item in dropitems: send_command(droid, 'take ' + item) print(play(run(read_program(sys.stdin))))
T = G or T T = F and T T = not T T = E or T T = D and T J = not C J = T and J # two squares out T = not D T = E or T T = B or T T = not T J = T or J # one square out T = not A J = T or J return J if __name__ == '__main__': inp = fileinput.input() program = read_program(inp) springscript = '\n'.join(line for line in springscript.split('\n') if line and not line.startswith('#')) + '\n' program.inputs = [ord(x) for x in springscript] program.run() print(''.join(chr(x) if x < 255 else str(x) for x in program.outputs))