def __init__(self, program): self.program = program self.grid = defaultdict(lambda: ' ', {(0, 0): '.'}) self.botpos = (0, 0) self.o2pos = None self.comp = IntComputer(program) self.dd = {1: (-1, 0), 2: (1, 0), 3: (0, -1), 4: (0, 1)}
def play(blocks, manual=False, verbose=True): # noqa score = 0 blocks += 1 # 1 for initial score ic = IntComputer(load_program('13/input')) ic.memory[0] = 2 game = np.zeros((20, 44), dtype=np.uint8) paddle = (0, 0) ball = (0, 0) with ic as proc: ctrl = None while not proc.terminated: for px in range(game.shape[0] * game.shape[1] + 1): try: x = proc.stdout.get(block=True, timeout=.2) y = proc.stdout.get(block=True, timeout=.2) t = proc.stdout.get(block=True, timeout=.2) except Empty: break if x == -1: blocks -= 1 score = t else: if t == 3: paddle = (x, y) elif t == 4: ball = (x, y) game[y, x] = t if verbose: print_game(game) print('\n--------\n', score) else: print('\r', ' ' * 20, '\r', f'{score:6d} {blocks:3d}', end='') if not manual: offset = ball[0] - paddle[0] if offset < 0: ctrl = -1 elif offset > 0: ctrl = 1 else: ctrl = 0 try: proc.stdin.put(ctrl, block=True, timeout=.2) ctrl = None except Full: pass else: try: while ctrl is None: try: ctrl = int(input('JOY: ')) except ValueError: ctrl = None proc.stdin.put(ctrl, block=True, timeout=1) ctrl = None except Full: pass print() return score
def part1(program): comp = IntComputer(program) out = comp.run_until_outputs() grid = defaultdict(lambda: 0) while len(out) == 3: x, y, tid = out grid[(x, y)] = tid out = comp.run_until_outputs() c = Counter(grid.values()) return c[2]
def test1(program): """ >>> test1([104,1125899906842624,99]) [1125899906842624] >>> test1([1102,34915192,34915192,7,4,7,99,0]) [1219070632396864] >>> test1([109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]) [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99] """ comp = IntComputer(program) return comp.run_program()
def main(): for x in range(100): noun = x for y in range(100): verb = y computer = IntComputer(retrieve_opcode()) computer.update(1, noun) computer.update(2, verb) run = computer.run() if run[0] == 19690720: print( f'noun: {noun}, verb: {verb}, answer: {100 * noun + verb}') break
def part1(program): comp = IntComputer(program) inputs = """\ NOT A J NOT B T OR T J NOT C T OR T J AND D J WALK """ comp.inputs.extend([ord(c) for c in inputs]) out = comp.run_program() # print(''.join([chr(x) for x in out[:-1]])) return out[-1]
def painter(h, mem): _x = _y = 0 direction = 'U' computer = IntComputer(mem, run_mode=ic.PAUSE_ON_OUTPUT) while not computer.halted: inp = h.get((_x, _y), 0) paint_to = computer.exec([inp]).get_last_output() if not computer.halted: turn_to = computer.exec([inp]).get_last_output() else: break h[(_x, _y)] = paint_to direction = DIRS[direction][turn_to] dx, dy = DELTAS[direction] _x += dx _y += dy
def robot(): # noqa map_ = np.ones((41, 41), dtype=np.uint8) * UNEXPLORED map_[0, :] = WALL map_[-1, :] = WALL map_[:, 0] = WALL map_[:, -1] = WALL start_position = map_.shape[0] // 2 + 1, map_.shape[1] // 2 + 1 ic = IntComputer(load_program('15/input')) with ic as proc: def act(command): try: proc.stdin.put(command, block=True, timeout=.2) except Full: pass try: response = proc.stdout.get(block=True, timeout=.2) except Empty: pass return response solve_maze(map_, start_position, act) map_[map_ == UNEXPLORED] = WALL print_map(map_, start_position) oxygen_position = np.where(map_ == OXYGEN) oxygen_position = oxygen_position[0][0], oxygen_position[1][0] flood = np.zeros_like(map_, dtype=np.int) - 1 flood_map(map_, oxygen_position, flood) print(np.max(flood)) print_flood(flood)
def try_loop_perm(program, settings): amps = [IntComputer(program, settings[n]) for n in range(5)] ampout = [0 for _ in range(5)] signal = 0 amp = 0 while -1 not in [amps[n].ip for n in range(5)]: signal = amps[amp].run_until_output(amps[amp].inputs + [signal]) ampout[amp] = signal amp = (amp + 1) % 5 return ampout[4]
def part1(program): comp = IntComputer(program) out = comp.run_until_prompt([ord(x) for x in instr]) print(''.join([chr(x) for x in out])) nv = 77 while True: cmd = input('?') if cmd == 'da': inp = drop_all() elif cmd == 'p': nv += 1 print(f'Trying combo {nv}') inp = drop_all() inp.extend(pu(nv)) inp.extend([ord(x) for x in 'north\n']) else: inp = [ord(c) for c in cmd+'\n'] print(inp) out = comp.run_until_prompt(inp) print(''.join([chr(x) for x in out]))
def part1(program): comp = IntComputer(program) grid = read_into_grid(comp) # display_dict_as_grid(grid) (minX, maxX), (minY, maxY) = [(min(c), max(c)) for c in zip(*grid)] total = 0 for x, y in product(range(minX + 1, maxX), range(minY + 1, maxY)): pos = (x, y) if grid[pos] == '#': if all(grid[c] == '#' for c in adjacent(pos)): total += x * y stuff(grid) return total
def part2(program): comp = IntComputer(program) comp.mem[0] = 2 # A L,6, R,8, R,12, L,6, L,8, # B L,10, L,8, R,12, # A L,6, R,8, R,12, L,6, L,8, # C L,8, L,10, L,6, L,6, # B L,10, L,8, R,12, # C L,8, L,10, L,6, L,6, # B L,10, L,8, R,12, # A L,6, R,8, R,12, L,6, L,8, # C L,8, L,10, L,6, L,6, # B L,10, L,8, R,12, movement = [ # broke things up manually 'A,B,A,C,B,C,B,A,C,B', 'L,6,R,8,R,12,L,6,L,8', 'L,10,L,8,R,12', 'L,8,L,10,L,6,L,6', 'n' ] for line in movement: comp.inputs.extend([ord(c) for c in line] + [10]) out = comp.run_program() # print(''.join([chr(x) for x in out[:-1]])) return out[-1]
def countblocks(): ic = IntComputer(load_program('13/input')) blocks = set() with ic as proc: while not proc.terminated: x = proc.stdout.get() y = proc.stdout.get() t = proc.stdout.get() if t == 2: blocks.add((x, y)) else: blocks.discard((x, y)) return len(blocks)
def part2(program): program = program[:] program[0] = 2 comp = IntComputer(program) grid = defaultdict(lambda: 0) ball, paddle = None, None score = 0 out = comp.run_until_outputs(0) while len(out) == 3: x, y, tid = out if x == -1: score = tid else: grid[(x, y)] = tid if tid == 4: ball = x if tid == 3: paddle = x # print(f'score={score}') # display_dict_as_grid(grid) v = get_input(ball, paddle) out = comp.run_until_outputs(v) return score
def run_bot(program, init_val): comp = IntComputer(program) panel = defaultdict(lambda: 0) botpos = (0, 0) botdir = 0 color = comp.run_until_output(init_val) turn = comp.run_until_output() while color != -1 and turn != -1: panel[botpos] = color botdir = (botdir + turn * 2 - 1) % 4 change = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)}[botdir] botpos = (botpos[0] + change[0], botpos[1] + change[1]) color = comp.run_until_output(panel[botpos]) turn = comp.run_until_output() return panel
def try_permutation(program, settings): signal = 0 for phase in settings: signal = IntComputer(program, [phase, signal]).run_program()[0] return signal
from itertools import permutations from intcomputer import IntComputer import intcomputer as ic with open("data/7.txt") as f: memory = [int(x) for x in f.readline().split(',')] orig_memory = copy.deepcopy(memory) max_thrust = -99999999999 perm = permutations([0, 1, 2, 3, 4]) for phases in perm: next_inp = 0 for phase in phases: memory = copy.deepcopy(memory) next_inp = IntComputer(memory).exec([phase, next_inp]).get_last_output() max_thrust = max(max_thrust, next_inp) print("Puzzle 7.1: ", max_thrust) max_thrust = -99999999999 perm = permutations([5, 6, 7, 8, 9]) for p in perm: computers = [] for i in range(5): computers.append( IntComputer(copy.deepcopy(memory), run_mode=ic.PAUSE_ON_OUTPUT)) i2 = 0 while [c.halted for c in computers] != [True] * 5:
def crun(memory, noun, verb, control): computer = IntComputer(memory) computer[1], computer[2] = noun, verb computer() if computer[0] == control: return 100 * noun + verb
import copy from intcomputer import IntComputer with open("data/2.txt") as f: memory = [int(x) for x in f.readline().split(',')] orig_memory = copy.deepcopy(memory) memory[1] = 12 memory[2] = 2 print("Puzzle 2.1: ", IntComputer(memory).exec().get_memory_at(0)) noun = 0 for n in range(100): memory = copy.deepcopy(orig_memory) memory[1] = n memory[2] = 0 if IntComputer(memory).exec().get_memory_at(0) > 19690720: noun = n - 1 break verb = 0 for v in range(100): memory = copy.deepcopy(orig_memory) memory[1] = noun memory[2] = v if IntComputer(memory).exec().get_memory_at(0) == 19690720: verb = v break
def main(): main_computer = IntComputer(retrieve_opcode()) main_computer.update(1, 12) main_computer.update(2, 2) run = main_computer.run() print(run)
def test(): computer1 = IntComputer([1, 0, 0, 0, 99]) assert computer1.run() == [2, 0, 0, 0, 99] computer2 = IntComputer([2, 3, 0, 3, 99]) assert computer2.run() == [2, 3, 0, 6, 99] computer3 = IntComputer([2, 4, 4, 5, 99, 0]) assert computer3.run() == [2, 4, 4, 5, 99, 9801] computer4 = IntComputer([1, 1, 1, 4, 99, 5, 6, 0, 99]) assert computer4.run() == [30, 1, 1, 4, 2, 5, 6, 0, 99]
def reset(): global src amps = [IntComputer(src) for _ in range(_AMPS)] return amps
def __str__(self): sstr = '**** SCORE: {} * BLOCKS: {} * PADDLE: {} * BALL: {} ****\n'\ .format(self.score, self.blocks, self.paddle, self.ball) for y in range(self.max_y): for x in range(self.max_x + 1): sstr = sstr + SCREEN[self.scr.get((x, y), EMPTY)] sstr += '\n' return sstr with open("data/13.txt") as f: memory = [int(x) for x in f.readline().split(',')] orig_memory = deepcopy(memory) computer = IntComputer(memory, run_mode=ic.RUN_TO_HALT).exec() print("Puzzle 13.1: ", sum([1 for item in computer.get_outputs()[2::3] if item == BLOCK])) memory = deepcopy(orig_memory) memory[0] = 2 computer = IntComputer(memory, run_mode=ic.PAUSE_ON_OUTPUT) out = [] while True: o = get_n_outputs(computer, [], 3) out.extend(o) if o[0] == -1: break
def part1(program): return sum( IntComputer(program).run_until_output([x, y]) for x, y in product(range(50), range(50)))
def probe(program, x, y): return IntComputer(program).run_until_output([x, y])
from intcomputer import IntComputer with open("data/9.txt") as f: memory = [int(x) for x in f.readline().split(',')] print("Puzzle 9.1: ", IntComputer(memory).exec([1]).get_last_output()) print("Puzzle 9.2: ", IntComputer(memory).exec([2]).get_last_output())
class Ship: def __init__(self, program): self.program = program self.grid = defaultdict(lambda: ' ', {(0, 0): '.'}) self.botpos = (0, 0) self.o2pos = None self.comp = IntComputer(program) self.dd = {1: (-1, 0), 2: (1, 0), 3: (0, -1), 4: (0, 1)} def run_step(self, d): pos = self.botpos out = self.comp.run_until_output(d) delta = self.dd[d] np = (pos[0] + delta[0], pos[1] + delta[1]) self.grid[np] = {0: '#', 1: '.', 2: '.'}[out] if out == 2: self.o2pos = np if out in [1, 2]: self.botpos = np return out def count_of_unknown(self): count = 0 for k, v in self.grid.items(): if v == '.': adj = [self.grid[a] for a in adjacent(k) if a in self.grid] if len(adj) < 4 or ' ' in adj: count += 1 return count def diplay_grid(self): m1, m3 = self.grid[self.botpos], self.grid[(0, 0)] m2 = self.grid[self.o2pos] if self.o2pos else None self.grid[self.botpos] = 'B' self.grid[(0, 0)] = '@' if self.o2pos: self.grid[self.o2pos] = 'O' display_dict_as_grid(self.grid) self.grid[self.botpos] = m1 self.grid[(0, 0)] = m3 if m2: self.grid[self.o2pos] = m2 # def explore_randomly(self, howlong=1000): # d = randint(1, 4) # for _ in range(howlong): # out = self.run_step(d) # if out == 0: # d = randint(1, 4) # if out in [1, 2]: # if randint(1, 5) == 1: # d = randint(1, 4) # def explore_2(self, howlong=1000): # d = randint(1, 4) # for _ in range(howlong): # out = self.run_step(d) # if out == 0: # d = (d + randint(0, 1) * 2 - 2) % 4 + 1 def explore_left(self, howlong=1000): d = randint(1, 4) for _ in range(howlong): out = self.run_step(d) if out == 0: d = right[d] else: d = left[d]
def part2(program): comp = IntComputer(program, 2) return comp.run_program()[0]