def valid(x, y, memory): inq = Queue() outq = Queue() t = IntCode(memory.copy(), inq, outq) t.start() inq.put(x) inq.put(y) t.join() return outq.get()
def run_robot(facing, pos, colour): inq = Queue() outq = Queue() robot = IntCode(memory.copy(), inq, outq) robot.start() grid = {} grid[pos] = colour inq.put(colour) DX = {0: 1, 1: 0, 2: -1, 3: 0} DY = {0: 0, 1: 1, 2: 0, 3: -1} while robot.is_alive(): colour = outq.get() turn = outq.get() grid[pos] = colour facing = (facing + (1 if turn else -1)) % 4 pos = (pos[0] + DX[facing], pos[1] + DY[facing]) inq.put(grid[pos] if pos in grid else 0) return grid
def part1(memory): max_signal = 0 max_order = [] for order in itertools.permutations([0, 1, 2, 3, 4], 5): signal = 0 input_queue = Queue() output_queue = Queue() for i in order: input_queue.put(i) input_queue.put(signal) cur_thread = IntCode(memory.copy(), input_queue, output_queue) cur_thread.start() cur_thread.join() signal = output_queue.get() if signal > max_signal: max_signal = signal max_order = order print(max_order, max_signal)
def part2(memory): max_signal = 0 max_order = [] for order in itertools.permutations([5, 6, 7, 8, 9], 5): signal = 0 queues = [Queue() for _ in range(5)] threads = [] for idx, phase in enumerate(order): queues[idx].put(phase) cur_thread = IntCode(memory.copy(), queues[idx], queues[(idx + 1) % 5]) threads.append(cur_thread) cur_thread.start() queues[0].put(0) for t in threads: t.join() signal = queues[0].get() if signal > max_signal: max_signal = signal max_order = order print(max_order, max_signal)
if grid.get((x-1, y)) in [4, 3, 2]: g.add_edge((x, y), (x-1, y)) if grid.get((x+1, y)) in [4, 3, 2]: g.add_edge((x, y), (x+1, y)) if grid.get((x, y-1)) in [4, 3, 2]: g.add_edge((x, y), (x, y-1)) if grid.get((x, y+1)) in [4, 3, 2]: g.add_edge((x, y), (x, y+1)) path = nx.dijkstra_path(g, (0, 0), pos) print(path) print(len(path) - 1) with open('15.in') as f: memory = [int(x.strip()) for x in f.read().split(',')] t = IntCode(memory.copy(), inq, outq) t.start() unexplored = {} moves = [] pos = (0, 0) oxygen = None while True: if pos not in unexplored: unexplored[pos] = [1, 2, 3, 4] if len(unexplored[pos]) > 0: back = False move = unexplored[pos].pop() else: back = True if len(moves) == 0: # back at start