def problem17a(camera_output=None): if camera_output is None: file_name = 'day17/problem17.txt' program = np.loadtxt(file_name, np.int32, delimiter=',') computer = Computer(program) camera_output = '' while not computer.done: output = computer.run() if output is not None: camera_output += chr(output) print(camera_output) lines = camera_output.split('\n') char_array = np.array([list(line) for line in lines if line]) intersections = [] n_rows, n_cols = char_array.shape for irow in range(n_rows): for icol in range(n_cols): if char_array[irow, icol] == '#': cross_row = ((irow > 0) and (char_array[irow-1, icol] == '#')) \ and ((irow < n_rows-1) and (char_array[irow+1, icol] == '#')) cross_col = ((icol > 0) and (char_array[irow, icol-1] == '#')) \ and ((icol < n_cols-1) and (char_array[irow, icol+1] == '#')) if cross_row and cross_col: coords = (irow, icol) intersections.append(coords) intersection_array = np.array(intersections) alignment = np.sum(np.prod(intersection_array, axis=1)) return alignment
def p1(lines): # All of the panels are currently black panels = defaultdict(int) painted = set() pos = ((0, 0), 0) def fetch(): while True: # provide 0 if the robot is over a black panel # or 1 if the robot is over a white panel yield panels[pos[0]] computer = Computer(lines[0]) computer.input = fetch() runnable = computer.run_output() try: while True: panels[pos[0]] = next(runnable) painted.add(pos[0]) turn = next(runnable) d = (pos[1] + (3 if turn == 0 else 1)) % 4 pos = ((pos[0][0] + directions[d][0], pos[0][1] + directions[d][1]), d) except StopIteration: pass return len(painted)
def run_network(): with open('day23_input.txt') as infile: program = list(map(int, infile.read().split(','))) computers = {} programs = {} for address in range(50): computer = Computer(program) computer.set_input([address]) computers[address] = computer programs[address] = computer.run_program() messages = {address: [] for address in range(50)} nat_value = None nat_y_sent = set() while True: for address, program in programs.items(): output = next(program) if output is not None: messages[address].append(output) if len(messages[address]) == 3: destination, x, y = messages.pop(address) if destination == 255: nat_value = (x, y) else: computers[destination].set_input((x, y)) messages[address] = [] idle = all( len(computer.inputs) == 0 for computer in computers.values()) if idle and nat_value: computers[0].set_input(nat_value) y = nat_value[1] if y in nat_y_sent: return y nat_y_sent.add(y) nat_value = None
def run(data): c = Computer.fromstring(data) c.run() layout, robot = parse_output(c.output) # print_board(layout) part_a = sum( r * c for r in range(1, len(layout) - 1) for c in range(1, len(layout[0]) - 1) if { layout[r][c], layout[r + 1][c], layout[r - 1][c], layout[r][c - 1], layout[r][c + 1] } == {'#'}) move_str = walk_scaffold(layout, robot) # Emprically determined sub_a = 'R,10,R,8,L,10,L,10' sub_b = 'R,8,L,6,L,6' sub_c = 'L,10,R,10,L,6' main = move_str.replace(sub_a, 'A').replace(sub_b, 'B').replace(sub_c, 'C') c = Computer.fromstring(data) c.memory[0] = 2 c.run(main + '\n' + sub_a + '\n' + sub_b + '\n' + sub_c + '\nn\n') # c.display_ascii() return part_a, c.output[-1]
def solve(d): inp = """OR E J OR H J AND D J OR A T AND B T AND C T NOT T T AND T J RUN """ p = 0 steps = 0 computer = Computer(d, ord(inp[p])) while True: steps += 1 retcode, retval = computer.step() if retcode == -1: break if retcode == 0 and retval == 3: p += 1 if p < len(inp): computer.set_input(ord(inp[p])) if retcode == 1 and retval > 255: return retval return steps
def p2(lines): screen = dict() score = 0 def fetch(): while True: ball = next((k for k, v in screen.items() if v == 4), None) paddle = next((k for k, v in screen.items() if v == 3), None) if not ball or not paddle: yield 0 if ball[0] < paddle[0]: yield -1 elif ball[0] > paddle[0]: yield 1 else: yield 0 seed = list(lines[0]) seed[0] = 2 computer = Computer(seed) computer.input = fetch() runnable = computer.run_output() try: while True: x, y, tile_id = next(runnable), next(runnable), next(runnable) if x == -1 and y == 0: score = tile_id else: screen[(x, y)] = tile_id except StopIteration: pass return score
def run(data): c = Computer.fromstring(data) c.run() part_a = sum(1 for *_, t in grouper(c.output, 3) if t == 2) c = Computer.fromstring(data) return part_a, play_game(c)
def run_part1(self, computer: Computer): computer = computer.copy() computer.break_on_output = True robot = Robot(computer) steps = robot.explore_for_oxygen() return str(len(steps))
def build(grid): q = deque([[(0, 0), Computer.load().program]]) station = (-1, -1) while q: position, program = q.popleft() output = -1 for delta, command in directions: move = tuple(map(add, delta, position)) computer = Computer(program.copy()) computer.inputs.append(command) while not computer.outputs: computer.tick() output = computer.outputs.popleft() if output != 0: if move not in grid: q.append([move, computer.program]) if output == 2: station = move grid[move] = output return station
def __init__(self, program, move_cb=None): self._cpu = Computer(program) self.location = Vector(0, 0) self._empty = set() self._walls = set() self._oxygen_system = None self._move_cb = move_cb
def check_sequence(program): perms = permutations(range(5, 10)) best_perm = None max_output = 0 for sequence in perms: input_val = 0 computers = { 'A': Computer(np.copy(program), [input_val, sequence[0]]), 'B': Computer(np.copy(program), [sequence[1]]), 'C': Computer(np.copy(program), [sequence[2]]), 'D': Computer(np.copy(program), [sequence[3]]), 'E': Computer(np.copy(program), [sequence[4]]), } routing = { 'A': 'B', 'B': 'C', 'C': 'D', 'D': 'E', 'E': 'A', } amp = 'A' last_output = None while not all([comp.done for comp in computers.values()]): output = computers[amp].run() next_amp = routing[amp] computers[next_amp].input_list.insert(0, output) amp = next_amp if output is not None: last_output = output if last_output > max_output: best_perm = sequence max_output = last_output return max_output, best_perm
def p2(lines): seed = list(lines[0]) seed[0] = 2 computer = Computer(seed) runnable = computer.run_output() # solved manually by looking at the view generated at part 1 # after writing the whole sequence, find repeating sequences fa = ['R', '12', 'L', '10', 'R', '12'] fb = ['L', '8', 'R', '10', 'R', '6'] fc = ['R', '12', 'L', '10', 'R', '10', 'L', '8'] mainseq = ['A', 'B', 'A', 'C', 'B', 'C', 'B', 'C', 'A', 'C'] cinput = '\n'.join([ ','.join(mainseq), ','.join(fa), ','.join(fb), ','.join(fc), ]) + '\nn\n' def fetch(): for c in cinput: yield ord(c) computer.input = fetch() for o in runnable: if o > 255: return o
def __init__(self, program): # direction 0 = up, 1 = left, 2 = down, 3 = right self.coords = np.zeros(2, dtype=np.int32) self.direction = 0 self.hull = dict() self.input_list = [] self.computer = Computer(program, self.input_list)
def get_ship_map(): robot = Computer(read("inputs/day_15.txt")) pos = (0, 0) ship_map = {} moves = [] # contains directions (value) we haven't attempted for each # coordinate (key) unexplored = {} while True: if pos not in unexplored: unexplored[pos] = [1, 2, 3, 4] if unexplored[pos]: back_tracking = False move = unexplored[pos].pop() else: back_tracking = True if not moves: # backtracked to start return ship_map prev = moves.pop() move = get_opposite(prev) robot.add_input(move) status = robot.run() if status in (SUCCESSFUL_MOVE, OXYGEN): pos = make_move(pos, move) ship_map[pos] = status if not back_tracking: moves.append(move)
def _part2(program, target): computer = Computer(program) noun = _search_noun(computer, 0, 100, target) verb = _search_verb(computer, noun, 0, 100, target) computer.run(noun, verb) assert computer.memory[0] == target print("Part 2:", noun * 100 + verb)
def part2(input): """ >>> import aoc_input as inp; part2(inp.read(5)) 7704130 """ ic = Computer(input, [5]) return ic.run()
def part2(input): """ >>> import aoc_input as inp; part2(inp.read(9)) 33343 """ ic = Computer(input, [2]) coords = ic.run() return coords
def problem5a(): file_name = 'day05/problem5.txt' program = np.loadtxt(file_name, np.int32, delimiter=',') computer = Computer(program, [1]) output = 0 while not output: output = computer.run() return output
def part1(input): """ >>> import aoc_input as inp; part1(inp.read(5)) 12896948 """ ic = Computer(input, [1]) ic.run() return ic.outputs[-1]
def compute(lines, permutation): signal = 0 for phase in permutation: computer = Computer(lines[0]) computer.input = iter([phase, signal]) computer.run_mode() signal = computer.output return signal
def main(): computer = Computer(inputs) computer.put(1) print(computer.eval()) computer = Computer(inputs) computer.put(2) print(computer.eval())
def program_springdroid(intcode_program): computer = Computer(intcode_program) computer.start() process_computer_output(computer) for line in JUMPSCRIPT: set_computer_input(computer, line) set_computer_input(computer, 'WALK') return process_computer_output(computer)
def part2(pc: intcode.Computer) -> int: for noun in range(100): for verb in range(100): pc.reset() pc.data[1], pc.data[2] = noun, verb pc.run() if pc.data[0] == 19690720: return 100 * noun + verb
def part1(input): """ >>> import aoc_input as inp; part1(inp.read(9)) 3780860499 """ ic = Computer(input, [1]) res = ic.run() return res
def update_position(self, x, y): self.input_list += [y, x] # didn't think I'd need to reset the program every time, but it didn't # work otherwise self.computer = Computer(np.copy(self._program), self.input_list) output = self.computer.run() self.map[y, x] = output return output
def run_part2(self, computer: Computer): computer = computer.copy() computer.break_on_output = True robot = Robot(computer) robot.explore_all() minutes = robot.fill_oxygen() return str(minutes)
class Robot(): def __init__(self, program): # direction 0 = up, 1 = left, 2 = down, 3 = right self.coords = np.zeros(2, dtype=np.int32) self.direction = 0 self.hull = dict() self.input_list = [] self.computer = Computer(program, self.input_list) def run(self): # detect color of curent panel, run program, paint, turn, and step # rinse and repeat while not self.computer.done: color = self.hull.get(tuple(self.coords), 0) self.input_list.insert(0, color) if len(self.input_list) != 1: logging.warning("Input list length: %d", len(self.input_list)) new_color = self.computer.run() if self.computer.done: break self.hull[tuple(self.coords)] = new_color turn_instruction = self.computer.run() if self.computer.done: break self.turn(turn_instruction) self.step() def turn(self, val): if val == 0: # turn left self.direction = (self.direction + 1) % 4 elif val == 1: # turn right self.direction = (self.direction - 1) % 4 else: raise ValueError("Turn value is {}.".format(val)) def step(self): if self.direction == 0: self.coords[1] += 1 elif self.direction == 1: self.coords[0] -= 1 elif self.direction == 2: self.coords[1] -= 1 elif self.direction == 3: self.coords[0] += 1 else: raise RuntimeError("Bad direction {}.".format(self.direction)) def show_hull(self): coords = np.array(list(self.hull.keys())) min_coords = np.min(coords, axis=0) coords -= min_coords max_coords = np.max(coords, axis=0) img = np.zeros(max_coords + 1, dtype=np.int32) for coord, color in self.hull.items(): new_coord = np.array(coord) - min_coords img[new_coord[0], new_coord[1]] = color plt.imshow(img.T, origin='lower') plt.savefig('problem11b.jpg')
class CheckPoint: def __init__(self, source): self.prog = [int(c) for c in source.split(',')] self.comp = Computer(self.prog) def __call__(self, inp): self.comp.reset(self.prog) self.comp.run(inp) return self.comp.output[0]
def run(value): output = [] cpu = Computer(opcodes) cpu.receive_input(value) while not cpu.halted: out = cpu.step() if out != None: output.append(out) return output
def _run_program(robot, program): computer = Computer(program) computer.write(robot.camera()) while not computer.is_halted: computer.step() if computer.num_outputs == 2: robot.paint(computer.read()) robot.move(computer.read()) computer.write(robot.camera())