def run(c, r): # Re-start everytime...uff vm = VM(data) vm.add_input(r) vm.add_input(c) vm.run() return vm.outputs.pop(0)
def run_painting_bot(initial_input): vm = VM(data) current_pos = (0, 0) BOARD = {current_pos: initial_input} direction = 0 while not vm.halted: if current_pos in BOARD: vm.add_input(BOARD[current_pos]) else: vm.add_input(0) vm.run() color = vm.outputs.pop(0) BOARD[current_pos] = color rotate_right = vm.outputs.pop(0) if rotate_right: direction = (direction + 1) % len(DR) else: direction = (direction - 1) % len(DR) current_pos = (current_pos[0]+DR[direction], current_pos[1]+DC[direction]) return BOARD
# print(room, door) new_room = parse_output(command(vm, door)) if new_room is None or new_room.name in SEEN: continue SEEN.add(new_room.name) new_pos = (pos[0] + DX[door], pos[1] + DY[door]) SHIP[new_pos] = new_room if navigate(door, new_room, new_pos) is None: command(vm, OPP[door]) continue return None # Parse all rooms in the ship vm = VM(data) vm.run() print(vm.outputs) room = parse_output(to_str(vm.outputs)) SHIP[pos] = room navigate('', room, pos) print(SHIP) vm = VM(data) vm.run() commands = [ 'south', 'south', 'south', 'south', 'take festive hat', 'north', 'north', 'north', 'take whirled peas', 'north', 'west', 'take pointer', 'east', 'north', 'take coin', 'north', 'take astronaut ice cream', 'north', 'west', 'take dark matter', 'south', 'take klein bottle', 'west', 'take mutex', 'west', 'south', 'drop dark matter', 'drop astronaut ice cream',
from utils import VM filename = 'input15.txt' with open(filename) as f: rawProgram = "".join( [s.strip() for s in f.readlines()]) memory = [int(i) for i in rawProgram.split(",")] moves = [None, (0, 1), (0, -1), (-1, 0), (1, 0)] vm = VM(memory) #vm.run(p) #vm.output start_pos = (0, 0) explored_open = set([start_pos]) queue = [(start_pos, [])] # Current pos, length, path to current oxygen_pos = None while queue: # Visit all states (x_pos, y_pos), path = queue.pop() # Follow the path to the start position for step in path: vm.run(step) assert(vm.output[-1] == 1) for command in range(1, 5): new_path = path + [command] vm.run(command) output = vm.output[-1]
from utils import VM from collections import deque, Counter, defaultdict import re # with open('data/day17_test.txt') as f: with open('data/day17.txt') as f: data = list(map(int, f.read().strip().split(','))) # 35 means # # 46 means . # 10 starts a new line vm = VM(data) vm.run() G = [] row = [] while vm.outputs: c = vm.outputs.pop(0) if c == 10: if len(row) > 0: G.append(row) row = [] else: row.append(chr(c)) R = len(G) C = len(G[3]) for r in range(R): print(''.join(G[r]))
# except: # print("Part 1: {}".format(vm.output[-1])) # break requirements = [ ([('A', False), ('B', False), ('C', False), ('D', True)], True), ([('D', False)], False), ([('A', False), ('B', True), ('C', True), ('D', True)], True), ([('A', True), ('B', False), ('D', True)], True), ([('A', True), ('B', True), ('C', True), ('D', True)], False), ([('C', False), ('D', True), ('E', False), ('F', False)], True), ([('A', True), ('B', True), ('C', False), ('D', True), ('E', False), ('F', True), ('G', False), ('H', False)], False), # ([('E', False), ('H', False)], False), # ([('A', False), ('B', True), ('C', True), ('D', True), ('E', True), # ('F', True), ('G', True)], True) ] while True: vm = VM(memory) strat, attempt_counter = random_requirements_strategy( requirements, 9, 15, True) vm_input = create_springscript(strat, part1=False) vm.run(vm_input) try: feedback = ''.join(chr(i) for i in vm.output) print(meets_requirements(strat[:-1], requirements, 9)) except: print("Part 2: {} after {} iterations".format(vm.output[-1]), attempt_counter) break
} vm, _ = make_move(vm, bw[direc]) traverse(()) # Navigate to the security checkpoint for step in rooms['Security Checkpoint']: vm, _ = make_move(vm, step) # Drop all items for it in have: vm, _ = make_move(vm, 'drop ' + it) # Try all item combinations for j in range(len(have)): considered_sets = list(itertools.combinations(have, j)) for ss in considered_sets: for it in ss: vm, _ = make_move(vm, 'take ' + it) vm, _ = make_move(vm, 'north') o = ''.join(map(chr, vm.output)) if vm.halted: print(o) break else: for it in ss: vm, _ = make_move(vm, 'drop ' + it) vm = VM(memory) part1(vm)
import numpy as np from scipy.signal import convolve2d from utils import VM filename = 'input17.txt' with open(filename) as f: rawProgram = "".join([s.strip() for s in f.readlines()]) memory = [int(i) for i in rawProgram.split(",")] vm = VM(memory) #vm.run(p) #vm.output while not vm.halted: vm.run(0) # The input doesn't matter chars = [chr(o) for o in vm.output] newline_pos = np.array(chars) == "\n" num_cols = np.where(newline_pos)[0][0] layout = np.reshape(np.array(chars)[~newline_pos], [-1, num_cols]) num_rows = layout.shape[0] intersection_filter = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) intersections = convolve2d(layout == '#', intersection_filter, boundary='symm', mode='same') == 5 left_dist = np.tile(np.expand_dims(np.arange(num_cols), 0), [num_rows, 1]) top_dist = np.tile(np.expand_dims(np.arange(num_rows), 1), [1, num_cols]) print("Part1: {}".format((intersections * left_dist * top_dist).sum()))
from collections import deque from collections import defaultdict import sys from utils import VM with open('data/day23.txt') as f: data = list(map(int, f.read().split(','))) vms = [VM(data) for _ in range(50)] for i, vm in enumerate(vms): vm.add_input(i) SEEN = set() Q = defaultdict(list) idle = 0 part1_done = False while True: for i, vm in enumerate(vms): vm.run() while len(vm.outputs) > 0: address = vm.outputs.pop(0) x = vm.outputs.pop(0) y = vm.outputs.pop(0) if address == 255: NAT = (x, y) if not part1_done: print('Part 1: ', y) part1_done = True else: Q[address].append((x, y))
layer.stride, index - 1) img = layer(img) elif isinstance(layer, torch.nn.modules.dropout.Dropout): temp_class = Layer('Dropout', img.shape, layer(img).shape, index, 0, 0, index - 1) img = layer(img) elif isinstance(layer, torch.nn.modules.linear.Linear): img = img.view(-1) temp_class = Layer('FC', img.shape, layer(img).shape, index, 0, 0, index - 1) img = layer(img) layer_list.append(temp_class) index += 1 vm1 = VM(1e5, 8e8, 1) vm2 = VM(1e5, 6e8, 2) vm3 = VM(1e5, 6e8, 3) vm_list = [vm1, vm2, vm3] for layer in layer_list: assigned = False if layer.dependence != -1: for vm in vm_list: if vm.check_dependence(layer): if vm.cal_distance(layer) != -1: vm.assign_layer(layer) assigned = True if not assigned: dis_list = [] for vm in vm_list:
from utils import VM # with open('data/day19_test.txt') as f: with open('data/day19.txt') as f: data = list(map(int, f.read().strip().split(','))) # Part 1 # ================================= # How many points are affected by the tractor beam in the 50x50 area # closest to the emitter? count = 0 for r in range(50): for c in range(50): vm = VM(data) vm.add_input(r) vm.add_input(c) vm.run() ans = vm.outputs.pop(0) count += ans print(ans if ans else ' ', end='') print() print('Part 1: ', count) # Part 2 # ================================= # Find the 100x100 square closest to the emitter that fits entirely # within the tractor beam; within that square, find the point closest # to the emitter. What value do you get if you take that point's X # coordinate, multiply it by 10000, then add the point's Y coordinate?
import numpy as np from random import sample import string from utils import VM filename = 'input23.txt' with open(filename) as f: rawProgram = "".join([s.strip() for s in f.readlines()]) memory = [int(i) for i in rawProgram.split(",")] num_machines = 50 vms = [] for i in range(num_machines): vm = VM(memory) vm.run([i]) vms.append(vm) vm_queues = [[] for i in range(num_machines)] step = 0 while True: # import pdb; pdb.set_trace() print(step, np.array([len(m) for m in vm_queues]).sum()) step += 1 if step == 10: break # Update inputs for i in range(num_machines): if vm_queues[i]: input_instr = [vm_queues[i].pop()]
# jump instructions = [ NOT('A', 'T'), AND('D', 'T'), OR('T', 'J'), NOT('B', 'T'), AND('D', 'T'), OR('T', 'J'), NOT('C', 'T'), AND('D', 'T'), OR('T', 'J'), WALK() ] vm = VM(data) vm.add_input(list(itertools.chain(*instructions))) vm.run() if vm.outputs[-1] > 0x110000: print('Part 1: ', vm.outputs[-1]) else: print(''.join(list(map(chr, vm.outputs)))) # Part 1 # ================================= # Successfully survey the rest of the hull by ending your program with RUN. # What amount of hull damage does it report? instructions = [ NOT('A', 'T'), AND('D', 'T'),
# Valid path elif out == 1: self.pos = new_pos self.board[new_pos] = True self.stack.extend([d, 0]) break # Part 1 # ================================= # What is the fewest number of movement commands required to move the # repair droid from its starting position to the location of the oxygen system? # Can't simply do a BFS. We need to backtrack as the intcode program # will have modified each time take a step, so we need to step back vm = VM(data) maze = Maze(vm) maze.run() print('Part 1: ', maze.oxygen[0]) # Part 2 # ================================= # How many minutes will it take to fill with oxygen? # Here we can simply BFS as we don't need the VM anymore as we # recorded the board SEEN = set() BOARD = maze.board Q = deque() Q.append((maze.oxygen[1],0))
import numpy as np from utils import VM filename = 'input19.txt' with open(filename) as f: rawProgram = "".join( [s.strip() for s in f.readlines()]) memory = [int(i) for i in rawProgram.split(",")] vm = VM(memory) grid_size = 50 collect_size = 2000 ship_width = 100 start_col = 0 beam_sum = 0 ray_ratio = 1.4 for i in range(collect_size): if i == 50: print("Part 1: {}".format(beam_sum)) next_start_col = np.inf prev_start_col = start_col beam_width = 0 zero_gap_patience = 2 for j in range(start_col, collect_size): vm.run([i, j]) int_output = vm.output[-1] vm = VM(memory) if int_output == 0: zero_gap_patience -= 1 if zero_gap_patience == 0: break
self.p = values[1] else: self.p += STEPS[opcode] elif opcode == LESS_THAN: self.write(write_to, int(values[0] < values[1])) self.p += STEPS[opcode] elif opcode == EQUALS: self.write(write_to, int(values[0] == values[1])) self.p += STEPS[opcode] elif opcode == ADJUSTBASE: self.rel_base += values[0] # print(self.program[self.p:self.p+2], self.rel_base) self.p += STEPS[opcode] else: BaseException(f'Unrecognized opcode: {opcode}.') # Part 1 # ================================= vm = VM(data) vm.add_input(1) vm.run() print('Part 1: ', vm.outputs.pop()) # Part 1 # ================================= vm = VM(data) vm.add_input(2) vm.run() print('Part 2: ', vm.outputs.pop())