def part1(data): amp_program = data inputs = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] input_pointer = 0 def input_function(): nonlocal input_pointer output = inputs[input_pointer] input_pointer += 1 return output phase_settings = permutations([0, 1, 2, 3, 4]) outputs = [] for phase_setting in phase_settings: input_pointer = 0 inputs = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for j in range(5): inputs[2 * j] = phase_setting[j] for amp in range(5): computer = IntcodeComputer(deepcopy(amp_program), input_function) computer.run_program() if amp == 4: outputs.append(computer.outputs[0]) break inputs[2 * amp + 3] = computer.outputs[0] return max(outputs)
def play(screen, program): if RENDER_GAME: curses.curs_set(0) y_max = 0 computer = IntcodeComputer(program, return_output=True, return_before_input=True) current_score = 0 game_tiles = {} while True: output = computer.run() if output is computer.sentinel_return: bx, px = ball_and_paddle_x(game_tiles) computer.append_inputs(-1 if bx < px else 1 if bx > px else 0) x = computer.run() else: x = output y = computer.run() tile_id = computer.run() if computer.halted(): break if x == -1 and y == 0: current_score = tile_id if RENDER_GAME: screen.addstr(y_max + 2, 0, f"Score => {current_score}") screen.refresh() else: game_tiles[(x, y)] = tile_id if RENDER_GAME: y_max = max(y_max, y) screen.addstr(y, x, COMPONENTS[tile_id]) screen.refresh() sleep(FRAME_RATE) return current_score
def Day05(program_file, input, output=False): VM = IntcodeComputer(program_file, input) while not VM.halted: result = VM.run() if result is not None: diagnostic_code = result return diagnostic_code
def part1(data): def inf(): return 0 scanner = IntcodeComputer(data, inf) scanner.run_program() scaffold = [[]] for output in scanner.outputs: if output != 10: scaffold[-1].append(output) else: scaffold.append([]) scaffold = scaffold[:-2] total = 0 for y in range(len(scaffold) - 1): for x in range(len(scaffold[0]) - 1): if x == 0 or y == 0: continue if scaffold[y][x] in (35, 94): intersection = True for pair in ((1, 0), (0, 1), (-1, 0), (0, -1)): if scaffold[y + pair[1]][x + pair[0]] == 46: intersection = False if intersection: total += x * y return total
def solution2(data: List[int]) -> int: computer = IntcodeComputer(data) instructions = [ "NOT C J\n", "AND D J\n", "NOT H T\n", "NOT T T\n", "OR E T\n", "AND T J\n", "NOT A T\n", "OR T J\n", "NOT B T\n", "NOT T T\n", "OR E T\n", "NOT T T\n", "OR T J\n", ] for instruction in instructions: computer.send_long(instruction) computer.send_long("RUN\n") computer.run_until_blocked() while computer.has_output(): value = computer.read() try: print(chr(value), end="") except ValueError: return value
def painted_panels(intcode_program: list[int], starting_input: int, get_image_meta: bool) -> dict[Position, int]: computer = IntcodeComputer(intcode_program, inputs=[starting_input], return_output=True) if get_image_meta: xmin = xmax = ymin = ymax = 0 panels_painted = {} position: Position = (0, 0) pointing = "U" while True: color = computer.run() if computer.halted(): break panels_painted[position] = color if get_image_meta: x, y = position xmin = min(xmin, x) xmax = max(xmax, x) ymin = min(ymin, y) ymax = max(ymax, y) direction = computer.run() position, pointing = move_robot(position, direction, pointing) computer.append_inputs(panels_painted.get(position, 0)) if get_image_meta: return panels_painted, (xmin, ymax), (abs(xmin) + xmax), (abs(ymin) + ymax) else: return panels_painted
def solve(input): intcodeComputer = IntcodeComputer(input, noun=12, verb=2) # part 1 intcodeComputer.run() print(intcodeComputer.memory[0]) # part 2, i'm lazy so i'll just brute force it for noun in range(0, 99): for verb in range(0, 99): intcodeComputer = IntcodeComputer(input, noun, verb) intcodeComputer.run() if intcodeComputer.memory[0] == 19690720: print((100 * noun) + verb) return
def solution1(data: List[int], noun=12, verb=2) -> int: computer = IntcodeComputer(data) computer.registers[1] = noun computer.registers[2] = verb while not computer.halted: computer.run() return computer.registers[0]
def __init__(self, program, visualize=0): self.computer = IntcodeComputer(program, [], "Arcade Cabinet") self.areamap = dict() self.visualize = visualize self.startpos = Position(0,0) self.areamap[self.startpos] = Field(self.startpos, 1, -1) self.currentpos = self.startpos
def part2(data): amp_program = data phase_settings = permutations([5, 6, 7, 8, 9]) max_output = 0 for phase_setting in phase_settings: last_output = 0 current_amp = 0 phase_given = [False, False, False, False, False] def input_function(): nonlocal last_output, phase_setting, current_amp, phase_given if not phase_given[current_amp]: output = phase_setting[current_amp] phase_given[current_amp] = True else: output = last_output return output computers = [] for x in range(5): computers.append(IntcodeComputer(deepcopy(amp_program), input_function)) while not computers[4].stopped: last_output = computers[current_amp].get_next_output() current_amp = (current_amp + 1) % 5 output = computers[4].outputs[-1] if output > max_output: max_output = output return max_output
def Day13(program_file, grid_init, part2=False, plot=False): def get_joystick(): """Simple AI tracking the ball position with the paddle.""" return np.sign(ball - paddle) # Set up grid (determined from wall positions) R, C = grid_init G = [[0 for _ in range(C)] for _ in range(R)] # Initialise Intcode program if part2: VM = IntcodeComputer(program_file, input=get_joystick) VM.override({0: 2}) # Buffer for score display at the top of screen row_buffer = 2 else: VM = IntcodeComputer(program_file) row_buffer = 0 # Carry on receiving output from program until it halts while True: c, r, tile = [VM.run() for _ in range(3)] if c == -1: score = tile if VM.halted: break elif tile == 3: paddle = c # Save paddle x-position elif tile == 4: ball = c # Save ball x-position G[r + row_buffer][c] = tile # Matplotlib plot if plot: plt.figure() plt.imshow(G, cmap='gist_stern') plt.axis('off') if part2: plt.text( 42.2, 0.6, "Score: " + str(score), fontsize=9, family='Consolas', color='white', horizontalalignment='right' ) if part2: return score return sum(x.count(2) for x in G)
def __init__(self, intcode: List[int]): self.intcode = intcode self.current_position = (0, 0) self.screen = defaultdict(int) self.intcode_computer = IntcodeComputer(intcode, self.get_input, self.generate_output) self.offset = 0 self.score = 0
def __init__(self, intcode: List[int]): self.intcode = intcode self.current_position = (0, 0) self.orientation = (0, 1) self.painting_area = defaultdict(int) self.intcode_computer = IntcodeComputer(intcode, self.get_input, self.generate_output) self.waiting_for_direction = False
def main(data): ic = IntcodeComputer(data, init=2) ic.run() while True: try: print(ic.output) except Empty: break
def get_result(data: List[int], x: int, y: int) -> int: computer = IntcodeComputer(data) computer.send(x) computer.send(y) computer.run_until_blocked() assert computer.has_output() result = computer.read() return result
def checkCoordinates(program, x, y): input_handler = InputModule(x, y) output_handler = OutputModule() intcodeComputer = IntcodeComputer(program, input_handler=input_handler, output_handler=output_handler) intcodeComputer.run() result = output_handler.result return result
def check(program, x, y): z = -1 def inf(): nonlocal x, y, z z += 1 return [x, y][z] return IntcodeComputer(program, inf).get_next_output()
def solution1(data: List[int]) -> int: computer = IntcodeComputer(data) computer.send(1) while not computer.halted: computer.run() result = 0 while result == 0: result = computer.read() return result
def main(data): for system_id in (1, 5): ic = IntcodeComputer(data, init=system_id) ic.run() while True: try: print(ic.output) except Empty: break
def __init__(self, program, free_play=False, auto=False, display=True): if free_play: program = program[:] program[0] = 2 self.computer = IntcodeComputer(program, [], "Arcade Cabinet") self.gamestate = dict() self.ball, self.tile = None, None self.auto = auto self.display = display
def main(data): for i in range(100): for j in range(100): ic = IntcodeComputer(data) ic.code[1] = i ic.code[2] = j ic.run() if ic.code[0] == OUTPUT: return i, j
def __init__(self, address: int, network_queue: asyncio.Queue): self.address = address self.state = NicState() self.input = asyncio.Queue() self.network_queue = network_queue self.computer = IntcodeComputer('day23.txt', self.get_input, self.put_output) self.input.put_nowait(address)
def moveRobot(puzzle_input, path): # transform path into series of movements turn = path[0][1] steps = 0 move_commands = [] for i, node in enumerate(path[1:]): if node[1] != Turn.NONE or i == len(path) - 2: if i == len(path) - 2: steps += 1 # starting new segment move_commands.append(('R' if turn == Turn.RIGHT else 'L') + str(steps)) steps = 1 turn = node[1] else: steps += 1 # look for patterns, decide on A, B, and C routines patterns = [] choosePatterns(move_commands, 0, patterns, 3) # decide what order patterns should go in start_index = 0 pattern_order = [] while start_index < len(move_commands): found_pattern = False sub_commands = move_commands[start_index:] for pattern_index, pattern in enumerate(patterns): if len(pattern) <= len(sub_commands) and sub_commands[:len( pattern)] == pattern: pattern_order.append(pattern_index) start_index += len(pattern) found_pattern = True break if not found_pattern: raise Exception( "Unable to find matching pattern for commands {} starting at {} with patterns {}" .format(move_commands, start_index, patterns)) # generate actual input robot_input = [] robot_input.append(','.join([chr(i + 65) for i in pattern_order])) for pattern in patterns: robot_input.append(getFinalCommandForMovementPattern(pattern)) robot_input = '\n'.join(robot_input) + '\nn\n' print(robot_input) # RERUN! puzzle_input = puzzle_input.strip() output = Output() intcodeComputer = IntcodeComputer(puzzle_input, input_handler=Input(robot_input), output_handler=output) intcodeComputer.memory[0] = 2 intcodeComputer.run() path = output.getPathOfScaffold()
def walkTheRegion(input_string, space): stdscr = curses.initscr() game = Game(space) intcodeComputer = IntcodeComputer(input_string, input_handler=InputModule(game, stdscr), output_handler=OutputModule( game, stdscr, 39, 13)) intcodeComputer.run() curses.endwin() return game
def part1(data): last_out = 1 direction_pointer = 0 DIRECTIONS = {1: (0, 1), 4: (1, 0), 2: (0, -1), 3: (-1, 0)} walls = set() current_pos = (0, 0) to_input = 1 def turn_right(): table = {1: 4, 2: 3, 3: 1, 4: 2} nonlocal to_input to_input = table[to_input] def turn_left(): table = {1: 3, 2: 4, 3: 2, 4: 1} nonlocal to_input to_input = table[to_input] def inf(): nonlocal to_input return to_input turtle = IntcodeComputer(data, inf) walls.add((current_pos[0], current_pos[1], 3)) while True: turn_left() check_wall = turtle.get_next_output() while check_wall == 0: walls.add((current_pos[0] + DIRECTIONS[to_input][0], current_pos[1] + DIRECTIONS[to_input][1])) turn_right() check_wall = turtle.get_next_output() current_pos = (current_pos[0] + DIRECTIONS[to_input][0], current_pos[1] + DIRECTIONS[to_input][1]) if check_wall == 2: walls.add((current_pos[0], current_pos[1], 2)) if current_pos == (0, 0): break bounds = [0, 0, 0, 0] for wall in walls: if wall[0] < bounds[0]: bounds[0] = wall[0] if wall[0] > bounds[2]: bounds[2] = wall[0] if wall[1] < bounds[1]: bounds[1] = wall[1] if wall[1] > bounds[3]: bounds[3] = wall[1] maze = [[0 for j in range(bounds[2] - bounds[0] + 1)] for i in range(bounds[3] - bounds[1] + 1)] for wall in walls: if len(wall) == 3: maze[wall[1] - bounds[1]][wall[0] - bounds[0]] = wall[2] else: maze[wall[1] - bounds[1]][wall[0] - bounds[0]] = 1 for line in maze: print("".join([str(x) for x in line]).replace("1", "█").replace("0", ' ').replace("2", "E")) return maze
def runner(seq): a = IntcodeComputer(INPUT, [0, seq[0]]) b = IntcodeComputer(INPUT, [seq[1]]) c = IntcodeComputer(INPUT, [seq[2]]) d = IntcodeComputer(INPUT, [seq[3]]) e = IntcodeComputer(INPUT, [seq[4]]) results = [] while 'HALTED' not in results: a_result = a.run() b.addInput(a_result) b_result = b.run() c.addInput(b_result) c_result = c.run() d.addInput(c_result) d_result = d.run() e.addInput(d_result) e_result = e.run() a.addInput(e_result) results = results + [a_result, b_result, c_result, d_result, e_result] return max([x for x in results if x != 'HALTED'])
def __init__(self, prog): self.p = direction.UP # pointing self.loc = (0,0) self.grid = {} self.grid[self.loc] = 1 self.brain = IntcodeComputer([], prog) self.painted = [] self.paint()
def part1_and_2(data): outputs = [] for i in (1, 2): def inf(): return i computer = IntcodeComputer(data, inf) computer.run_program() outputs.append(computer.outputs[0]) return outputs
async def run_program(program: List[int], input_signal: int): input = Queue() output = Queue() computer = IntcodeComputer(program, input, output) input.put_nowait(input_signal) await computer.execute() while not output.empty(): print(output.get_nowait())
def main(data): powers = [] for perm in permutations(range(5)): q = LifoQueue() q.put(0) for phase in perm: ic = IntcodeComputer(data, in_queue=q, out_queue=q) q.put(phase) ic.run() powers.append(q.get()) print(max(powers))