def __init__(self) -> None: with open_fixture("day15") as fp: data = decode(fp.readline()) self.vm = IntcodeVM(data) self.grid = Grid() self.pos = Position(0, 0) self.oxygen_system_pos = Position(0, 0)
def start_nic(program, address, channels): def non_blocking_input(): if not non_blocking_input.address_sent: non_blocking_input.address_sent = True return address if non_blocking_input.this_packet: return non_blocking_input.this_packet.popleft() try: non_blocking_input.this_packet = channels[address].get(timeout=0.1) except Empty: return -1 else: return non_blocking_input.this_packet.popleft() non_blocking_input.address_sent = False non_blocking_input.this_packet = None def route_output(val): route_output.this_packet.append(val) if len(route_output.this_packet) == 3: dest, x, y = route_output.this_packet route_output.this_packet = [] channels[dest].put(deque([x, y])) route_output.this_packet = [] IntcodeVM(program, non_blocking_input, route_output).run()
def run_springscript(script, mode): input = deque(ord(c) for c in script + f"\n{mode}\n") output = deque() IntcodeVM(SPRINGSCRIPT_VM_CODE, input.popleft, output.append).run() if output[-1] > 255: return output.pop() for c in output: sys.stdout.write(chr(c))
def __init__( self, wake_up: bool = False, ): with open_fixture("day17") as fp: data = decode(fp.readline()) self.vm = IntcodeVM(data) if wake_up: self.vm.data[0] = 2
def firstVisiblePoint(): for i in range(1, 50): for j in range(1, 50): UserInput.append((i, j)) for spot in UserInput: robot = IntcodeVM(memry.copy()) robot.updateInput([spot[0], spot[1]]) robot.run() if robot.prgOutput == 1: return (spot[0], spot[1])
def __init__(self, data: Data) -> None: self.vm = IntcodeVM(data, trap_input=self._trap_input) self.score = 0 self.frame = 0 self.init_block_count = 0 self.last_good_frame = 0 self.last_good_state = data.copy() self.last_miss_x = 0 self.last_paddle_x = 0 self.failed = False self.moves: Optional[List[int]] = None self.stdscr: Any = None
def run_interactive(program): def input_reader(): if input_reader.last_input: return input_reader.last_input.popleft() for c in input(): input_reader.last_input.append(ord(c)) input_reader.last_input.append(ord("\n")) return input_reader.last_input.popleft() input_reader.last_input = deque() def output(output): sys.stdout.write(chr(output)) IntcodeVM(program, input_reader, output).run()
def collect_all_items(program, item_paths): command_list = [] for path, item in item_paths: if item[0] == "Checkpoint": continue command_list.extend(path) command_list.append(f"take {item}") command_list.extend(OPPOSITES[step] for step in reversed(path)) command_list.extend(next(path for path, item in item_paths if item[0] == "Checkpoint")) for _, item in item_paths: command_list.append(f"drop {item}") vm = IntcodeVM(program, CommandInput(command_list), lambda c: None) vm.run() return vm
def thrust(data: Data, phase_sequence: Sequence[int]) -> int: vms = [IntcodeVM(data, [phase]) for phase in phase_sequence] E = vms[len(vms) - 1] v = 0 i = 0 while not E.halted: vm = vms[i] vm.io_push(v) while not vm.halted: vm.step() if vm.stdout: v = vm.io_pop() break i = (i + 1) % len(phase_sequence) return v
def runScript(scr): vm = IntcodeVM(prog) inp = [] for line in scr.splitlines(): inp += list(map(ord, line)) inp.append(10) vm.addInput(inp) vm.runToBlock() s = '' ans = 0 for i in vm.output: try: s += chr(i) except ValueError: ans = i return ans, s
def run(initialBlock): vm = IntcodeVM(data) grid = defaultdict(lambda: BLACK) grid[(0, 0)] = initialBlock direction = 'N' x = 0 y = 0 halted = False while not halted: vm.addInput([grid[(x, y)]]) halted = vm.runToBlock() grid[(x, y)] = vm.output[-2] direction = TURNS[direction][vm.output[-1]] dx, dy = DIRECTIONS[direction] x += dx y += dy return grid
## Read tries.txt to see me trying all the inputs. Solved today mostly by hand! from intcode import IntcodeVM file = open('input.txt', 'r') memry = [] for line in file: memry = line.split(',') comp = IntcodeVM(memry) while True: comp.run() print(chr(comp.prgOutput), end="")
from intcode import IntcodeVM from collections import defaultdict file = open('input.txt', 'r') memry = [] computers = [] inputFrom = defaultdict(lambda: []) NATInput = [] for line in file: memry = line.split(',') for i in range(50): comp = IntcodeVM(memry.copy()) comp.updateInput(i) computers.append(comp) while len(NATInput) == 0: for i in range(50): computers[i].run() if computers[i].output: inputFrom[i].append(computers[i].prgOutput) if len(inputFrom[i]) >= 3: who = inputFrom[i].pop(0) xtoSend = inputFrom[i].pop(0) ytoSend = inputFrom[i].pop(0) if who != 255: computers[who].updateInput(xtoSend) computers[who].updateInput(ytoSend) else:
from common import * from intcode import IntcodeVM prog = filemap(int, "day17.txt", ',') vm = IntcodeVM(prog) vm.runToBlock() s = '' for i in vm.output: s += chr(i) print(s) dg = s.strip().split('\n') grid = defaultdict(lambda: False) SCAFFOLD = set('#^><v') HEIGHT = len(dg) WIDTH = len(dg[0]) robotPos = None robotDirection = None DIRS = {'^': 'N', 'v': 'S', '>': 'W', '<': 'E'} for y in range(HEIGHT): for x in range(WIDTH): if dg[y][x] in SCAFFOLD: grid[(x, y)] = True if dg[y][x] in '^v<>': robotPos = (x, y) robotDirection = DIRS[dg[y][x]]
def readGrid(x, y): vm = IntcodeVM(prog) vm.addInput([x, y]) vm.runToBlock() return vm.output[-1]
def run(data: Data, stdin: Optional[Data] = None) -> Data: vm = IntcodeVM(data, stdin=stdin) vm.run() return vm.stdout
def test_part1_example3(self): data = decode("104,1125899906842624,99") vm = IntcodeVM(data) vm.run() self.assertEqual(vm.stdout[0], 1125899906842624)
def test_part1_example2(self): data = decode("1102,34915192,34915192,7,4,7,99,0") vm = IntcodeVM(data) vm.run() self.assertGreaterEqual(vm.stdout[0], 1000000000000000)
def __init__(self, program: Data) -> None: self.vm = IntcodeVM(program) self.grid = Grid() self.orientation = Orientation.UP self.position = (0, 0)
from intcode import IntcodeVM file = open('input.txt', 'r') memry = [] for line in file: memry = line.split(',') howBigIsTheScan = 50 UserInput = [] for i in range(howBigIsTheScan): for j in range(howBigIsTheScan): UserInput.append((i, j)) howManyTracks = 0 for spot in UserInput: robot = IntcodeVM(memry.copy()) robot.updateInput([spot[0], spot[1]]) robot.run() howManyTracks += robot.prgOutput print(howManyTracks)
def test_part2(self): with open_fixture("day09") as fp: data = decode(fp.readline()) vm = IntcodeVM(data, [2]) vm.run() self.assertListEqual(vm.stdout, [49122])
from common import * from intcode import IntcodeVM data = filemap(int, "day15.txt", ',') grid = defaultdict(lambda: None) x, y = 0, 0 WALL = 0 OPEN = 1 TARGET = 2 vm = IntcodeVM(data) BACKWARDS = {1: 2, 2: 1, 3: 4, 4: 3} def explore(x, y): for direction in range(1, 5): dx, dy = DIRECTIONS[direction] nx = x + dx ny = y + dy if grid[(nx, ny)] is not None: continue vm.addInput([direction]) vm.runToBlock() grid[(nx, ny)] = vm.output[-1] if vm.output[-1] in (OPEN, TARGET):
def test_part1_example1(self): data = decode( "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99") vm = IntcodeVM(data) vm.run() self.assertListEqual(vm.stdout, data)
from common import * from intcode import IntcodeVM prog = filemap(int, "day23.txt", ',') COMPUTERS = 50 comps = [] qs = [] for i in range(COMPUTERS): comps.append(IntcodeVM(prog)) comps[i].addInput([i]) comps[i].runToBlock() qs.append(deque([])) # done = False nat = None part1 = False lastY = None while True: idle = True for ix, c in enumerate(comps): if len(qs[ix]) > 0: idle = False while qs[ix]: x, y = qs[ix].popleft() c.addInput([x, y]) else: c.addInput([-1]) c.runToBlock()
command_list.append(f"drop {item}") vm = IntcodeVM(program, CommandInput(command_list), lambda c: None) vm.run() return vm def try_combination(vm, items, direction): output_parser = OutputParser() vm = vm.clone(CommandInput([f"take {item}" for item in items] + [direction]), output_parser) vm.run() return output_parser.checkpoint_failed(), output_parser.password() def try_all_object_combos(vm, item_paths): direction = next(item[1] for path, item in item_paths if item[0] == "Checkpoint") items = [item for path, item in item_paths if item[0] != "Checkpoint"] for r in range(len(items)): for combination in combinations(items, r): failed, password = try_combination(vm, combination, direction) if not failed: return password with open("input.txt") as input_file: PROGRAM = [int(instruction) for instruction in input_file.read().split(",")] # run_interactive(PROGRAM) ITEM_PATHS = list(find_items(IntcodeVM(PROGRAM, None, None), "", [])) AT_CHECKPOINT = collect_all_items(PROGRAM, ITEM_PATHS) print(f"Part One: {try_all_object_combos(AT_CHECKPOINT, ITEM_PATHS)}")
### (!A && D) || (!B && D) || (!C && D && H) from intcode import IntcodeVM file = open('input.txt', 'r') memry = [] for line in file: memry = line.split(',') robot = IntcodeVM(memry) UserInput = [] answer = "NOT A T\nNOT B J\nAND D J\nOR T J\nNOT C T\nAND D T\nAND H T\nOR T J\nRUN\n" for a in answer: UserInput.append(ord(a)) robot.updateInput(UserInput) while robot.finished == False: robot.run() if robot.prgOutput < 255: print(chr(robot.prgOutput), end="") else: print(robot.prgOutput)
def checkPoint(thisPoint): robot = IntcodeVM(memry.copy()) robot.updateInput([thisPoint[0], thisPoint[1]]) robot.run() return robot.prgOutput