def solve_second_part(p, cmds): p[0] = 2 c = IntComputer(p) print(cmds) c.inputs = [ord(a) for a in cmds] + [10, ord('n'), 10] print(c.inputs) _map = "" halted = False while not halted: if c.pause: c.continue_program() else: c.run_program() if len(c.outputs) > 0: v = c.outputs.pop() if v < 256: _map += chr(v) if c.halted: halted = True print(_map) print(v) print(c.outputs)
def run_springscript(p, script): c = IntComputer(p) c.inputs = [ord(a) for a in script] print(c.inputs) _map = "" halted = False while not halted: if c.pause: c.continue_program() else: c.run_program() if len(c.outputs) > 0: v = c.outputs.pop() if v < 256: _map += chr(v) if c.halted: halted = True print(_map) print(v) return v
def find_max_output_no_feedback(code_immutable): phase_setting = 0 input_signal = 0 input_count = 0 max_output = 0 amplifier_index = 0 def input_func(): nonlocal input_count input = phase_setting if input_count == 0 else input_signal input_count += 1 return input def output_func(val): nonlocal input_signal nonlocal max_output input_signal = val if amplifier_index == 4: max_output = max(max_output, val) for perm in itertools.permutations(list(range(5))): input_signal = 0 for amplifier_index in range(5): input_count = 0 phase_setting = perm[amplifier_index] IntComputer(code_immutable, input_func, output_func).run() return max_output
def p2(inp, debug=False): if DISPLAY: import pygame as pg mode = MPX data = np.array([0, 0, 0]) if DISPLAY: pg.init() screen = pg.display.set_mode((GRIDSIZE[0] * 16, GRIDSIZE[1] * 16)) grid = pg.surface.Surface(GRIDSIZE) ballpos = 0 padpos = 0 score = 0 def display(): pg.transform.scale(grid, (GRIDSIZE[0] * 16, GRIDSIZE[1] * 16), screen) pg.display.flip() def events(): for ev in pg.event.get(): if ev.type == pg.QUIT: sys.exit(0) def read(): nonlocal display, events, ballpos, padpos if DISPLAY: events() display() return np.sign(padpos - ballpos) def write(val): nonlocal mode, data, grid, ballpos, padpos, score data[mode] = val if mode == MTI: if data[MPX] == -1 and data[MPY] == 0: score = data[MTI] else: if DISPLAY: pg.draw.circle(grid, COLORS[data[MTI]], (data[MPX], data[MPY]), 0) if data[MTI] == 3: ballpos = data[MPX] elif data[MTI] == 4: padpos = data[MPX] mode = (mode + 1) % MMX robot = IntComputer("2" + inp[1:], name="Day 13", readf=read, writef=write, debug=debug) robot.run() return score
def bothParts(inp, debug=False): grid = np.zeros((GRIDSIZE, GRIDSIZE), dtype=np.int8) rX, rY, rA = GRIDMID, GRIDMID, 0 readingColor = True seen = set() def read(): nonlocal grid, rX, rY return grid[rX, rY] def write(val): nonlocal grid, rX, rY, rA, readingColor if readingColor: grid[rX, rY] = val seen.add((rX, rY)) else: if val == 0: rA = np.mod(rA - np.pi / 2, np.pi * 2) else: rA = np.mod(rA + np.pi / 2, np.pi * 2) rX += int(np.sin(rA)) rY += int(np.cos(rA)) readingColor = not readingColor robot = IntComputer(inp, name="Day 11", readf=read, writef=write, debug=debug) robot.run() p1 = len(seen) ### Part 2 grid.fill(0) grid[GRIDMID, GRIDMID] = 1 rX, rY, rA = GRIDMID, GRIDMID, (-np.pi / 2) readingColor = True robot.run() coords = np.argwhere(grid) mx, my = coords.min(axis=0) Mx, My = coords.max(axis=0) img = grid[mx : Mx + 1, my : My + 1] return ( p1, "\n".join(map(lambda row: "".join(map(str, row)), img)) .replace("0", " ") .replace("1", "█"), )
def scan(): global text, in_buf s = 0 c = IntComputer(text, f_in) rep = {0: '.', 1: '#'} f_edges = [] r_edges = [] points = {} for x in range(1074, 1179): in_beam = False for y in range(1724, 1830): in_buf.append(x) in_buf.append(y) c.run() if c.output: o = c.output.pop() s += o if o == 1 and not in_beam: f_edges.append((x, y)) in_beam = True if in_beam and o == 0: r_edges.append((x, y - 1)) in_beam = False points[(x, y)] = o print(rep[o], end="") c.reset() print() import math f_thetas = [] f_edges.pop(0) r_edges.pop(0) for p in f_edges: f_thetas.append(math.degrees(math.atan(p[0] / p[1]))) r_thetas = [] for p in r_edges: r_thetas.append(math.degrees(math.atan(p[0] / p[1]))) print(f_thetas) print(r_thetas) f_avg = sum(f_thetas) / len(f_thetas) r_avg = sum(r_thetas) / len(r_thetas) print(f_avg) print(r_avg) print("min/max f", min(f_thetas), max(f_thetas)) print("min/max r", min(r_thetas), max(r_thetas))
def p1(inp, debug=False): scaffolds = ''.join( map(chr, IntComputer(inp, name="ASCII", debug=debug).run())) scaffolds = np.array(lmap(list, scaffolds.strip().splitlines())) psum = 0 for x in range(1, scaffolds.shape[0] - 1): for y in range(1, scaffolds.shape[1] - 1): if scaffolds[x, y] == '#' and scaffolds[ x + 1, y] == '#' and scaffolds[x, y + 1] == '#' and scaffolds[ x - 1, y] == '#' and scaffolds[x, y - 1] == '#': psum += x * y return psum
def p2(inp, debug=False): x = 0 y = 500 # arbitrary optimization in_beam = lambda x, y: IntComputer( inp, name="Tractorbeam", inp=[x, y], debug=debug).run()[0] while 1: y += 1 while 1: if in_beam(x, y): if in_beam(x + 99, y - 99): return x * 10000 + (y - 99) else: x -= 3 # arbitrary optimization break x += 1
def tractor_beam(x, y, p): c = IntComputer(p) c.inputs = [x, y] result = 0 halted = False while not halted: if c.pause: c.continue_program() else: c.run_program() if len(c.outputs) > 0: result = c.outputs.pop() if c.halted: halted = True return result
def check(x, y): global text, in_buf outs = [] c = IntComputer(text, f_in) in_buf.append(x) in_buf.append(y) c.run() outs.append(c.output.pop()) c.reset() in_buf.append(x + 99) in_buf.append(y) c.run() outs.append(c.output.pop()) c.reset() in_buf.append(x) in_buf.append(y + 99) c.run() outs.append(c.output.pop()) return all(o == 1 for o in outs)
def p1(inp, debug=False): grid = np.zeros(GRIDSIZE, dtype=np.int8) mode = MPX data = np.array([0, 0, 0]) def write(val): nonlocal grid, mode data[mode] = val if mode == MTI: grid[data[MPX], data[MPY]] = data[MTI] mode = (mode + 1) % MMX robot = IntComputer(inp, name="Day 13", writef=write, debug=debug) robot.run() return grid[grid == 2].size
def find_max_output_with_feedback(code_immutable): amp_count = 5 max_output = 0 def input_func(): input = phase_setting if not phase_setting_was_read[ amplifier_index] else input_signal phase_setting_was_read[amplifier_index] = True return input def output_func(val): nonlocal input_signal, max_output input_signal = val if amplifier_index == 4: max_output = max(max_output, val) return True for perm in itertools.permutations(list(range(5, 10))): input_signal = 0 amplifier_index = 0 phase_setting_was_read = [False for _ in range(amp_count)] computers = [ IntComputer(code_immutable, input_func, output_func) for _ in range(amp_count) ] its = 0 while True: phase_setting = perm[amplifier_index] exit_code = computers[amplifier_index].run() if exit_code != "interrupt" and amplifier_index == 4: break amplifier_index = (amplifier_index + 1) % amp_count its += 1 return max_output
def run_turtle(code, start_color): global dirs turtle = IntComputer(code, [start_color], 2) painted = defaultdict(int) x, y = 0, 0 d = 0 ys = [] xs = [] turtle.run() while not turtle.halted: color = turtle.output.pop(0) turn = turtle.output.pop(0) painted[(x, y)] = color d = (d + (1 if turn == 1 else -1)) % 4 x += dirs[d][0] y += dirs[d][1] ys.append(y) xs.append(x) turtle.inbuf.append(painted[(x, y)]) turtle.run() return (painted, xs, ys)
def solve_first_part(p): c = IntComputer(p) _map = "" halted = False while not halted: if c.pause: c.continue_program() else: c.run_program() if len(c.outputs) > 0: _map += chr(c.outputs.pop()) if c.halted: halted = True print(_map) m = str_to_map(_map) intersections = find_intersections(m) c = calibrate(intersections) print(c) return m
code = f.read() in_bufs = [[i] for i in range(50)] def f_in(id): global in_bufs if in_bufs[id]: return in_bufs[id].pop(0) else: return -1 network = [] for i in range(50): network.append(IntComputer(code, f_in, i, 3)) NAT = (None, None) last_y = 0 first = True while any(not x.halted for x in network): if all(len(x) == 0 for x in in_bufs) and all(c.waiting for c in network): in_bufs[0].append(NAT[0]) in_bufs[0].append(NAT[1]) if NAT[1] == last_y: print("Part 2:", last_y) raise SystemExit() last_y = NAT[1] for i, c in enumerate(network): if not c.halted:
def p2(inp, debug=False): program = """A,B,A,B,C,B,A,C,B,C L,12,L,8,R,10,R,10 L,6,L,4,L,12 R,10,L,8,L,4,R,10 n """ # Solved by hand; notes: # ................................#####.............. # ................................#...#.............. # ................................#...#.............. # ................................#...#.............. # ................................#...#.............. # ................................#...#.............. # ..........................###########.............. # ..........................#.....#.................. # ..........................#.....#.................. # ..........................#.....#.................. # ..........................#.....#.................. # ..........................#.....#.................. # ......................###########.................. # ......................#...#........................ # ......................#...#........................ # ......................#...#........................ # ......................#...#########................ # ......................#...........#................ # ..........#...........#...........#................ # ..........#...........#...........#................ # ..........#...........#####.......#................ # ..........#...............#.......#................ # ..........#...............#.......#................ # ..........#...............#.......#................ # ..........#...........#######.....#................ # ..........#...........#...#.#.....#................ # ..........#.........#############.#...############# # ..........#.........#.#...#.#...#.#...#............ # ..........#####.....#.#############...#............ # ..............#.....#.....#.#...#.....#............ # ..............#.....#.....#######.....#............ # ..............#.....#.......#.........#............ # ..............#.....#.......#.........#............ # ..............#.....#.......#.........#............ # ..............#.....#.......###########............ # ..............#.....#.............................. # ....###########.....#.............................. # ....#...............#.............................. # ....#.....#########.#########...................... # ....#.....#.......#.........#...................... # ....#.....#.......#.........#...................... # ....#.....#.......#.........#...................... # ###########.......#.........#...................... # #...#.............#.........#...................... # #...#.............#.........#...................... # #...#.............#.........#...................... # #...#.............#.........#...................... # #...#.............#.........#...................... # #####.............###########...................... # L,12,L,8,R,10,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,L,6,L,4,L,12,R,10,L,8,L,4,R,10,L,6,L,4,L,12,L,12,L,8,R,10,R,10,R,10,L,8,L,4,R,10,L6,L4,L12,R,10,L,8,L,4,R,10 # LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF LFFFFFFFFFFFFLFFFFFFFFRFFFFFFFFFFRFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF LFFFFFFLFFFFLFFFFFFFFFFFF RFFFFFFFFFFLFFFFFFFFLFFFFRFFFFFFFFFF # L,12,L,8,R,10,R,10 # L,6,L,4,L,12 # R,10,L,8,L,4,R,10 # ABABCBACBC ret = -1 def write(val): nonlocal ret if val < 128: sys.stdout.write(chr(val)) else: ret = val IntComputer("2" + inp[1:], name="ASCII", inp=lmap(ord, program), writef=write, debug=debug).run() return ret
def p1(inp, debug=False): return pipe( it.product(range(50), repeat=2), map(list), map(lambda coord: IntComputer( inp, name="Tractorbeam", inp=coord, debug=debug).run()[0]), sum)
from intcode import IntComputer with open("1.ss") as f: sscrpt = f.read() in_buf = [ord(c) for c in list(sscrpt)] def f_in(): global in_buf return in_buf.pop(0) with open("input.txt") as f: c = IntComputer(f.read(), f_in) c.run() while not c.halted: out = c.output.pop(0) if out > 128: print("Part 1:", out) break #print(chr(out), end="") c.run() with open("2.ss") as f: sscrpt = f.read() in_buf = [ord(c) for c in list(sscrpt)] with open("input.txt") as f: c = IntComputer(f.read(), f_in)
else: self.been_painted.add(self.current_pos) if ins: self.white_panels.add(self.current_pos) else: self.white_panels.discard(self.current_pos) self.next_ins_is_direction = True robot = Robot() args, lines = parse_args_and_get_input() code_immutable = parse_program(lines[0]) if args.part_one: IntComputer(code_immutable, robot.get_current_color, robot.receive_instruction).run() print(len(robot.been_painted)) else: robot.white_panels.add(Point(0, 0)) IntComputer(code_immutable, robot.get_current_color, robot.receive_instruction).run() paint = "" for y in range(8): for x in range(80): if Point(x, y) in robot.white_panels: paint += "#" else: paint += " " paint += "\n"
def p1(inp, debug=False): print(f"Running {inp} with input [1]...\n") return IntComputer(inp, inp=[1], name="Part 1", debug=debug).run()
def run_game(p): c = IntComputer(p) board = {} x = 0 y = 0 board[(x, y)] = Tile(".") halted = False first_loop = True next_cmd = 0 counter = 0 visit_nodes(c, board, (0, 0)) o_point = find_oxygen(board) print(print_board(board)) print(o_point) min_dist = shortest_path(board, (0, 0), o_point) print(min_dist) print(longest_path(board, o_point)) # while not halted: # should_halt = False # c.input_index = 0 # c.inputs = [CMDS_LIST[next_cmd]] # if c.pause: # c.continue_program() # else: # c.run_program() # if counter != 0 and counter % 10 == 0: # print_board(board) # counter += 1 # if not c.halted: # output = c.outputs.pop() # if output == MOVED: # m = VALID_MOVES[CMDS_LIST[next_cmd]] # board[(x, y)].visited[next_cmd] = True # x += m[0] # y += m[1] # print(f"m ({x}, {y}) = '.'") # t = Tile(".") # t.visited[(next_cmd - 1) % 4] = True # board[(x, y)] = t # if output == WALL: # m = VALID_MOVES[CMDS_LIST[next_cmd]] # tx = x + m[0] # ty = y + m[1] # board[(x, y)].visited[next_cmd] = True # t = Tile("#") # t.visited[(next_cmd - 1) % 4] = True # board[(tx, ty)] = t # print(f"w ({tx}, {ty}) = '#'") # if output == OXYGEN_SYSTEM: # print(f"({x}, {y}) = 'O'") # m = VALID_MOVES[CMDS_LIST[next_cmd]] # x += m[0] # y += m[1] # board[(x, y)] = "O" # halted = True # print(f"w cur_cmd = {CMD_TO_STR[CMDS_LIST[next_cmd]]}") # next_cmd = get_next_cmd(board, next_cmd, x, y) # print(f"w next_cmd = {CMD_TO_STR[CMDS_LIST[next_cmd]]}\n===") # else: # halted = True print(print_board(board)) return 0
def p1(inp): print(f"Running {inp} with input [1]...\n") return IntComputer(inp, inp=[1], name="Day 5/1", debug=True).run()
def bothParts(inp, debug=False): grid = np.full(GRIDSIZE, UNKNOWN) grid[GRIDMID] = FREE pos = np.array(GRIDMID) cur_move = 0 last_turn = 0 ret, ret2 = -1, -1 if DISPLAY: import pygame as pg pg.init() screen = pg.display.set_mode( (GRIDSIZE[0] * SCALE, GRIDSIZE[1] * SCALE)) gridsurf = pg.surface.Surface(GRIDSIZE) def display(): for ev in pg.event.get(): if ev.type == pg.QUIT: sys.exit(0) pg.surfarray.blit_array(gridsurf, grid) pg.draw.circle(gridsurf, 0xE8214C, tuple(pos), 0) pg.transform.scale(gridsurf, (GRIDSIZE[0] * SCALE, GRIDSIZE[1] * SCALE), screen) pg.display.flip() def read(): nonlocal cur_move, pos, last_turn move = cur_move ORDER = [-1, 0, 1] for o in ORDER: _move = (move + o) % len(DIRECTIONS) last_turn = o npos = pos + DIRECTIONS[_move][1] cell = grid[npos[0], npos[1]] if cell != WALL: break cur_move = _move return DIRECTIONS[cur_move][0] def write(val): nonlocal grid, pos, cur_move, ret, ret2 npos = pos + DIRECTIONS[cur_move][1] if val == 0: if grid[npos[0], npos[1]] == UNKNOWN: cur_move = (cur_move - last_turn) % len(DIRECTIONS) grid[npos[0], npos[1]] = WALL elif val == 1: grid[npos[0], npos[1]] = FREE pos = npos elif val == 2: grid[npos[0], npos[1]] = OXYGEN pos = npos ret = dijkstra(grid, GRIDMID, MODE_LEN, display) ret2 = dijkstra(grid, tuple(np.array(np.where(grid == OXYGEN))[:, 0]), MODE_MAX, display) if ret != -1: return IntComputer.ABORT if DISPLAY: display() droid = IntComputer(inp, readf=read, name="Droid", writef=write, debug=debug) droid.run() return ret, ret2
from common import parse_args_and_get_input from intcode import parse_program, IntComputer def output(val): print("PRINT {}".format(val)) args, lines = parse_args_and_get_input() code_immutable = parse_program(lines[0]) # takes no input and produces a copy of itself as output. test1 = "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99" test2 = "1102,34915192,34915192,7,4,7,99,0" # should output a 16-digit number. test3 = "104,1125899906842624,99" # should output the large number in the middle. #IntComputer(parse_program(test1), lambda: 1, output).run() #IntComputer(parse_program(test2), lambda: 1, output).run() #IntComputer(parse_program(test3), lambda: 1, output).run() if args.part_one: IntComputer(code_immutable, lambda: 1, output).run() else: IntComputer(code_immutable, lambda: 2, output).run()
return map def bfs(map, start, goal): seen = set() dist = {start:0} q = [start] while len(q) > 0: cur = q.pop(0) if map[cur] == goal: return dist[cur] ns = [n for n in neighbors(cur) if map[n] != 0 and n not in seen] for n in ns: seen.add(n) dist[n] = dist[cur]+1 q.append(n) # if goal not found, returns max depth of search return dist[cur] with open("input.txt") as f: robot = IntComputer(f.read(), f_dir) map = scout(robot) #print_map(map) print("Part 1:", bfs(map, (0,0), 2)) print("Part 2:", bfs(map, dest, None))
from intcode import IntComputer def f_in(): return 0 with open("input.txt") as f: codestring = f.read() comp = IntComputer(codestring, f_in) s = '' comp.run() while not comp.halted: s += chr(comp.output.pop(0)) comp.run() lines = s.strip().split('\n') r_pos = None rev_dir = {(0, -1): 0, (1, 0): 1, (0, 1): 2, (-1, 0): 3} moves = [(0, -1), (1, 0), (0, 1), (-1, 0)] r_ors = ['^', '>', 'v', '<'] r_dir = 0 total = 0 for i in range(1, len(lines)-1): for j in range(1, len(lines[i])-1): if lines[i][j] == '#': if lines[i][j+1] == '#' and lines[i][j-1] == '#' and lines[i+1][j] == '#' and lines[i-1][j] == '#': total += i * j
in_buf = [] def f_in(): global in_buf return in_buf.pop(0) def has_in(): return len(in_buf) > 0 def send_in(s): global in_buf for c in s: in_buf.append(ord(c)) in_buf.append(10) with open("input.txt") as f: c = IntComputer(f.read(), f_in, has_in) while True: c.run() while c.output: print(chr(c.output.pop(0)), end="") c.run() instr = input() send_in(instr)
score = 0 inputs = {'j': -1, 'k': 0, 'l': 1} bx = 0 px = 0 joystick = 0 def get_joystick(): global joystick return joystick with open("input2.txt") as f: c = IntComputer(f.read(), get_joystick, 3) part1 = False c.run() while not c.halted: x, y = c.output.pop(0), c.output.pop(0) tile_id = c.output.pop(0) if (x == -1 and y == 0): score = tile_id else: pixels[(x, y)] = tile_id if not part1 and tile_id == 2: boxcount += 1 if tile_id == 4: #time.sleep(0.01)
from intcode import IntComputer with open("input.txt") as f: s = f.read() c = IntComputer(s, [1]) c.run() print("Part 1:", c.output[0]) c = IntComputer(s, [2]) c.run() print("Part 2:", c.output[0])