def run_intcode(inputfile, noun=None, verb=None): """Runs the Intcode provided in inputfile Parameters ---------- inputfile : str Name/path of file that contains the puzzle input noun : int Fixed value to put into memory[1] verb : int Fixed value to put into memory[2] """ memory = IntcodeVM.read_intcode(inputfile) if noun is not None: memory[1] = noun if verb is not None: memory[2] = verb machine = IntcodeVM(memory) machine.run() return machine
def paint_hull(inputfile, hull={}): """Launches the emergency hull painting robot with the specified Intcode source file Parameters ---------- inputfile: str Path/Filename of Intcode source code hull : dict<(int,int): int> Initial state of the hull """ robot_pos = (0, 0) robot_dir = (0, -1) machine = IntcodeVM(inputfile, silent=True) machine.run() while machine.waiting: color, turn = machine.resume([hull.get(robot_pos, BLACK)]) hull[robot_pos] = color robot_dir = TURNS[robot_dir][turn] robot_pos = (robot_pos[0] + robot_dir[0], robot_pos[1] + robot_dir[1]) return hull
def move_robot(inputfile, moves, screen): source = IntcodeVM.read_intcode(inputfile) drawer = GridDrawer(screen) source[0] = 2 machine = IntcodeVM(source, silent=True, output_func=drawer.add_output) outputs = machine.run(moves) sleep(2) return outputs.pop()
def play_game(inputfile, screen): source = IntcodeVM.read_intcode(inputfile) # Insert coin... source[0] = 2 # Boot up arcade machine machine = IntcodeVM(source, silent=True) grid = {} score = 0 total_bricks = 0 max_y = 0 move = None # Game loop while machine.waiting: if move is None: outputs = machine.run() else: outputs = machine.resume([move]) for o in range(0, len(outputs), 3): x, y, tile = outputs[o:o + 3] if x == -1 and y == 0: score = tile else: screen.print_at(SYMBOLS[tile], x * 3, y, COLORS[tile]) grid[(x, y)] = tile if total_bricks == 0: total_bricks = sum(1 for pos in grid if grid[pos] == BLOCK) if max_y == 0: max_y = max(grid.keys())[1] screen.print_at( "Blocks left: %s / %s " % (sum(1 for pos in grid if grid[pos] == 2), total_bricks), 5, max_y + 1) screen.print_at("Score: %s" % score, 5, max_y + 2) screen.move(0, 0) screen.refresh() sleep(0.01) # Breakout AI!! paddle = [key for key in grid if grid[key] == PADDLE][0] ball = [key for key in grid if grid[key] == BALL][0] if paddle[0] < ball[0]: move = 1 elif paddle[0] > ball[0]: move = -1 else: move = 0 screen.print_at("All done, press ENTER to exit!", 5, max_y // 2) screen.refresh() input()
def one_run(inputfile): max_thruster = 0 code = IntcodeVM.read_intcode(inputfile) machine = IntcodeVM(code) for phases in permutations([0, 1, 2, 3, 4]): last_output = 0 for phase in phases: inputs = [phase, last_output] outputs = machine.run(inputs) last_output = outputs.pop() if last_output > max_thruster: max_thruster = last_output return max_thruster
def __init__(self, source, computers=50): self.computers = [] self.packets = [] self.outputs = [] self.idle = [] self.nat_package = None self.last_nat_package = None for c in range(computers): computer = IntcodeVM(source, silent=True) self.idle.append(0) self.packets.append([]) output = computer.run([c]) self.outputs.append(output) computer.stepwise = True self.computers.append(computer)
def create_grid(inputfile): source = IntcodeVM.read_intcode(inputfile) machine = IntcodeVM(source, silent=True) outputs = machine.run() grid = [] line = [] for output in outputs: if output == 10: if len(line) > 0: grid.append(line) line = [] else: line.append(chr(output)) return grid
def maze(screen): # Initialise droid droid = IntcodeVM( IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")), False, True) # One run to determine the dimensions of the grid droid.run() area_map, _ = explore(droid) minx = min(pos[0] for pos in area_map) maxx = max(pos[0] for pos in area_map) miny = min(pos[1] for pos in area_map) maxy = max(pos[1] for pos in area_map) dimensions = (minx, miny, maxx, maxy) # Actual run with visualization droid.run() area_map, distance_map = explore(droid, screen=screen, dimensions=dimensions) os_pos = [pos for pos in area_map if area_map[pos] == OS][0] # breadth-first algorithm for spreading the oxygen frontiers = [os_pos] minutes = 0 while len(frontiers) > 0: new_frontiers = [] for frontier in frontiers: for (dx, dy) in DIRECTIONS.values(): new_frontier = (frontier[0] + dx, frontier[1] + dy) if area_map.get(new_frontier, WALL) == FREE: area_map[new_frontier] = OS draw_map(area_map, None, screen, dimensions) new_frontiers.append(new_frontier) frontiers = new_frontiers if len(frontiers) > 0: minutes = minutes + 1 input() print("Part 1: %s" % distance_map[os_pos]) print("Part 2: %s" % minutes)
def feedback_loop(inputfile): max_thruster = 0 code = IntcodeVM.read_intcode(inputfile) for phases in permutations([5, 6, 7, 8, 9]): done = False #Initialise machines machines = [] for phase in phases: machine = IntcodeVM(code) machine.run([phase]) machines.append(machine) last_output = 0 while not done: for machine in machines: last_output = machine.resume([last_output])[-1] if not machine.waiting: done = True if last_output > max_thruster: max_thruster = last_output return max_thruster
# eprint(addr, '>', *outpkts[addr]) recaddr = outpkts[addr][0] if recaddr == 255: natpkt = outpkts[addr][1:] else: Q[recaddr].append(outpkts[addr][1]) Q[recaddr].append(outpkts[addr][2]) outpkts[addr] = [] return vm_write vms = [IntcodeVM(prog) for _ in range(50)] for i, vm in enumerate(vms): vm.read = vmr(i) vm.write = vmw(i) for vm in vms: vm.reset() while not all(idle): for vm in vms: vm.run(n_in=1, resume=True) if all(idle): break last_nat_y = natpkt[1]
def bfs_farthest(maze, src): visited = set() queue = deque([(0, src)]) while queue: dist, node = queue.popleft() if node not in visited: visited.add(node) for n in filter(lambda n: n not in visited, neighbors4(maze, *node)): queue.append((dist + 1, n)) return dist advent.setup(2019, 15) fin = advent.get_input() program = list(map(int, fin.read().split(','))) vm = IntcodeVM(program) startpos = (0, 0) maze, oxygen = wall_follower(vm, startpos) min_dist = bfs_shortest(maze, startpos, oxygen) advent.print_answer(1, min_dist) time = bfs_farthest(maze, oxygen) advent.print_answer(2, time)
#!/usr/bin/env python3 from utils.all import * fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## from lib.intcode import IntcodeVM prog = get_ints(fin, True) vm = IntcodeVM(prog) def vm_write(v): if v > 127: print('>>>>>>>>>>>', v) sys.exit(0) else: sys.stdout.write(chr(v)) # vm.write = vm_write # (!A+!B+!C)D asm1 = """\ OR A T AND B T AND C T NOT T T
destination, *packet = self.out_packet self.out_packet = [] if destination == 255: nat_packet = packet else: network[destination].packet_queue.extend(packet) return vm_write advent.setup(2019, 23) fin = advent.get_input() program = list(map(int, fin.read().split(','))) network = [IntcodeVM(program) for _ in range(50)] nat_packet = None for i, vm in enumerate(network): vm.read = vm_read_for(vm) vm.write = vm_write_for(vm) vm.idle = False vm.unserviced_reads = 0 vm.packet_queue = deque([i]) vm.out_packet = [] while nat_packet is None: for vm in network: vm.run(n_in=1, resume=True) last_nat_y = nat_packet[1]
#!/usr/bin/env python3 from utils.all import * fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## from lib.intcode import IntcodeVM prog = get_ints(fin, True) vm = IntcodeVM(prog) n = 0 for i in range(50): for j in range(50): out = vm.run([i, j], n_out=1) if not out: break if out[0] == 1: n += 1 # print(n) advent.submit_answer(1, n) # PART 2: # Visualize, copy in text editor and solve by hand # using a regex: (1{100}.+\n){100}
miny = min(y for _, y in grid) maxy = max(y for _, y in grid) height = maxx - minx + 1 width = maxy - miny + 1 matrix = [([' '] * width) for _ in range(height)] for x in range(height): for y in range(width): if grid[minx + x, miny + y] == WHITE: matrix[x][y] = '#' return matrix advent.setup(2019, 11) fin = advent.get_input() program = list(map(int, fin.read().split(','))) robot = IntcodeVM(program) grid = run_robot(robot, BLACK) n_painted = len(grid) advent.print_answer(1, n_painted) grid = run_robot(robot, WHITE) pic = sparse_to_matrix(grid) pic = ''.join(''.join(x) + '\n' for x in pic) # Can't really print this nicely, but whatever advent.print_answer(2, '\n' + pic)
else: output = computer.resume() if len(output) > 0: self.idle[c] = 0 self.outputs[c].extend(output) def handle_outputs(self): for c in range(len(self.computers)): if len(self.outputs[c]) < 3: continue end = (len(self.outputs[c]) // 3) * 3 for o in range(0, end, 3): dest = self.outputs[c][o] x = self.outputs[c][o + 1] y = self.outputs[c][o + 2] if dest == 255: self.nat_package = [x, y] else: self.packets[dest].append([x, y]) self.outputs[c] = self.outputs[c][end:] source = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")) network = Network(source) print("Part 1: %s" % network.run()) print("Part 2: %s" % network.run(True))
#!/usr/bin/env python3 from utils import advent from lib.intcode import IntcodeVM advent.setup(2019, 5) fin = advent.get_input() program = list(map(int, fin.read().split(','))) vm = IntcodeVM(program) out = vm.run([1])[-1] advent.print_answer(1, out) out = vm.run([5])[-1] advent.print_answer(2, out)
from lib.intcode import IntcodeVM except ImportError: print("Intcode library could not be found") exit(1) def load_input(filename): with open(filename, "r") as file: inputs = [int(line) for line in file] # Add an extra zero at the end so the Intcode program knows when to stop reading inputs.append(0) return inputs code1 = IntcodeVM.read_intcode(os.path.join(currentdir, "01_part1.ic")) machine = IntcodeVM(code1) print("Testcases") outputs = machine.run([12, 0]) assert outputs.pop() == 2 outputs = machine.run([14, 0]) assert outputs.pop() == 2 outputs = machine.run([1969, 0]) assert outputs.pop() == 654 outputs = machine.run([100756, 0]) assert outputs.pop() == 33583 inputs = load_input(os.path.join(currentdir, "testinput.txt")) outputs = machine.run(inputs)
break if ok: A = ','.join(func_a) B = ','.join(func_b) C = ','.join(func_c) if len(A) <= 20 and len(B) <= 20 and len(C) <= 20: return A, B, C advent.setup(2019, 17) fin = advent.get_input() program = list(map(int, fin.read().split(','))) vm = IntcodeVM(program) out = vm.run() grid = ''.join(map(chr, out)).strip().splitlines() rows, columns = len(grid), len(grid[0]) answer = 0 for r in range(1, rows - 1): for c in range(1, columns - 1): if grid[r][c] == SCAFFOLD: n = sum((grid[rr][cc] == SCAFFOLD for rr, cc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)))) if n == 4: answer += r * c
def run_program(self, code, inputs=[]): """Helper method to initialise an IntcodeVM, run it and return the machine itself and the output of the run""" machine = IntcodeVM(code) outputs = machine.run(inputs) return machine, outputs
import os import sys currentdir = os.path.dirname(os.path.abspath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from lib.intcode import IntcodeVM code = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")) machine = IntcodeVM(code) outputs = machine.run([1]) print("Part 1: %s" % outputs.pop()) outputs = machine.run([5]) print("Part 2: %s" % outputs.pop())
import os import sys from itertools import combinations currentdir = os.path.dirname(os.path.abspath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) try: from lib.intcode import IntcodeVM except ImportError: print("Intcode library could not be found") exit(1) source = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")) machine = IntcodeVM(source, silent=True) # Path to security checkpoint picking up all safe items walkthrough = [ "east", "east", "take semiconductor", "north", "take planetoid", "west", "take food ration", "west", "west", "take monolith", "east", "east", "north", "take space law space brochure", "east", "take jam", "west", "north", "north", "take weather machine", "south", "south", "south", "east", "north", "take antenna", "south", "south", "east", "south", "south", "east", "drop food ration", "drop weather machine", "drop antenna", "drop space law space brochure", "drop jam", "drop semiconductor", "drop planetoid", "drop monolith" ] items = [ "food ration", "weather machine", "antenna", "space law space brochure", "jam", "semiconductor", "planetoid", "monolith"
#!/usr/bin/env python3 from utils.all import * fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## from lib.intcode import IntcodeVM prog = get_ints(fin, True) vm = IntcodeVM(prog) Q = deque() N, S, E, W = 'north', 'south', 'east', 'west' def vm_read_for(self): def vm_read(): if not Q: line = input() if line == 'n': line = N elif line == 's': line = S elif line == 'e': line = E elif line == 'w': line = W Q.extend(map(ord, line + '\n'))
def game(stdscr, program): stdscr.clear() curses.curs_set(False) program[0] = 2 vm = IntcodeVM(program) screen = {} n_tiles = 0 while True: x, y, tile = vm.run([0], resume=True, n_out=3) if (x, y) != (-1, 0): screen[x, y] = tile if len(screen) == n_tiles: break n_tiles = len(screen) grid = build_grid(screen) pad = curses.newpad(100, 100) del screen make_move = True redraw = False paddle_x = 0 inp = [0] score = 0 while True: out = vm.run(inp, resume=True, n_out=3) if not out: break x, y, tile = out if (x, y) == (-1, 0): score = tile else: if tile in (BALL, PADDLE) and REV_TILE_MAP[grid[y][x]] == EMPTY: redraw = True grid[y][x] = TILE_MAP[tile] if tile == BALL and make_move: if x > paddle_x: inp = [1] elif x < paddle_x: inp = [-1] make_move = False elif tile == PADDLE and not make_move: paddle_x = x make_move = True if redraw: redraw = False ok = display(pad, grid, score) if not ok: return 1 sleep(1) return 0
#!/usr/bin/env python3 from utils.all import * fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## from lib.intcode import IntcodeVM prog = get_ints(fin, True) vm = IntcodeVM(prog) def vm_write(v): if 0 <= v <= 0x7f: sys.stderr.write(chr(v)) else: print('==================== NON ASCII:', v) # Dump initial grid # vm.write = vm_write # vm.run() grid = [ '........#######..........................', '........#.....#..........................', '........#.....#..........................', '........#.....#..........................',
from lib.intcode import IntcodeVM fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## program = get_ints(fin, True) BLACK, WHITE = 0, 1 LEFT, RIGHT = 0, 1 NORTH, SOUTH, EAST, WEST = 'NSEW' robot = IntcodeVM(program) grid = defaultdict(lambda: BLACK) pos = (0,0) ############## Uncomment for part 2 ############ # grid[pos] = WHITE ################################################ curdir = NORTH first = True deb = False while True: # print(curdir, pos, grid[pos] if pos in grid else '?') if first:
def test_loading(self): """Program should load correctly from input file""" program = IntcodeVM.read_intcode( os.path.join(currentdir, "testinput1.txt")) self.assertListEqual(program, [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50])
Path/Filename of Intcode source code hull : dict<(int,int): int> Initial state of the hull """ robot_pos = (0, 0) robot_dir = (0, -1) machine = IntcodeVM(inputfile, silent=True) machine.run() while machine.waiting: color, turn = machine.resume([hull.get(robot_pos, BLACK)]) hull[robot_pos] = color robot_dir = TURNS[robot_dir][turn] robot_pos = (robot_pos[0] + robot_dir[0], robot_pos[1] + robot_dir[1]) return hull hull = paint_hull(IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt"))) print("Part 1: %s" % len(hull.keys())) print_hull(hull) hull = paint_hull( IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")), {(0, 0): WHITE}) print("Part 2:") print_hull(hull)
#!/usr/bin/env python3 from utils.all import * from lib.intcode import IntcodeVM fin = advent.get_input() # eprint(*fin, sep='') timer_start() ################################################## program = get_ints(fin, True) vm = IntcodeVM(program) screen = set() out = vm.run() for i in range(0, len(out), 3): x, y, t = out[i:i + 3] if t == 2: screen.add((x, y)) # if t == 3: # paddle = x, y # print(paddle) # print(paddle) advent.submit_answer(1, len(screen)) # def display(screen):
try: from lib.intcode import IntcodeVM except ImportError: print("Intcode library could not be found") exit(1) def run_sprintcode(machine, code): outputs = machine.run("\n".join(code)) for output in outputs: if output > 255: return output else: print(chr(output), end="") source = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")) machine = IntcodeVM(source, silent=True) code1 = ["OR A J", "AND B J", "AND C J", "NOT J J", "AND D J", "WALK", ""] print("Part 1: %s" % run_sprintcode(machine, code1)) code2 = [ "OR A J", "AND B J", "AND C J", "NOT J J", "AND D J", "OR H T", "OR E T", "AND T J", "RUN", "" ] print("Part 2: %s" % run_sprintcode(machine, code2))