Advent of Code 2016

--- Day 12: Leonardo's Monorail --- You finally reach the top floor of this building: a garden with a slanted glass ceiling. Looks like there are no more stars to be had. While sitting on a nearby bench amidst some tiger lilies, you manage to decrypt some of the files you extracted from the servers downstairs. According to these documents, Easter Bunny HQ isn't just this building - it's a collection of buildings in the nearby area. They're all connected by a local monorail, and there's another building not far from here! Unfortunately, being night, the monorail is currently not operating. You remotely connect to the monorail control systems and discover that the boot sequence expects a password. The password-checking logic (your puzzle input) is easy to extract, but the code it uses is strange: it's assembunny code designed for the new computer you just assembled. You'll have to execute the code and get the password. The assembunny code you've extracted operates on four registers (a, b, c, and d) that start at 0 and can hold any integer. However, it seems to make use of only a few instructions: - cpy x y copies x (either an integer or the value of a register) into register y. - inc x increases the value of register x by one. - dec x decreases the value of register x by one. - jnz x y jumps to an instruction y away (positive means forward; negative means backward), but only if x is not zero. The jnz instruction moves relative to itself: an offset of -1 would continue at the previous instruction, while an offset of 2 would skip over the next instruction. For example: cpy 41 a inc a inc a dec a jnz a 2 dec a The above code would set register a to 41, increase its value by 2, decrease its value by 1, and then skip the last dec a (because a is not zero, so the jnz a 2 skips it), leaving register a at 42. When you move past the last instruction, the program halts. After executing the assembunny code in your puzzle input, what value is left in register a?

In [1]:
from collections import defaultdict

In [2]:
class Assembunny:
    
    def __init__(self):
        self.registers = defaultdict(int)
        self.pointer = 0
        
    def _add_to_register(self, register, value):
        self.registers[register] = value
        
    def copy(self, register, value):
        try:
            value = int(value)
        except ValueError:
            value = self.registers[value]
        self._add_to_register(register, value)
        
    def increase(self, register):
        self.registers[register] += 1
        
    def decrease(self, register):
        self.registers[register] -= 1
        
    @staticmethod
    def is_number(n):
        try:
            n = int(n)
        except ValueError:
            return False
        return True
        
    def jump(self, index, register=None):
        if register is not None and (self.registers[register] != 0 or 
                                     self.is_number(register)):
            self.pointer += index
        else:
            self.pointer += 1
            
    def execute(self, instructions):
        while True:
            try:
                instruction = instructions[self.pointer]
                instruction = instruction.split()
                if instruction[0] == 'cpy':
                    self.copy(instruction[-1], instruction[1])
                    self.jump(1)
                elif instruction[0] == 'inc':
                    self.increase(instruction[-1])
                    self.jump(1)
                elif instruction[0] == 'dec':
                    self.decrease(instruction[-1])
                    self.jump(1)
                else:
                    self.jump(int(instruction[-1]), instruction[1])
            except IndexError:
                return self.registers

In [3]:
# Test
data = [
    'cpy 41 a',  # set register a to 41, 
    'inc a',     # increase its value by 1, (42)
    'inc a',     # increase its value by 1, (43)
    'dec a',     # decrease its value by 1, (42)
    'jnz a 2',   # skip the last dec a
    'dec a'
]

assembunny = Assembunny()
assert(assembunny.execute(data)['a'] == 42)

In [4]:
data = [line.strip() for line in open('data/day_12.txt', 'r')]

In [5]:
%%time 

assembunny = Assembunny()
res = assembunny.execute(data)


CPU times: user 840 ms, sys: 4 ms, total: 844 ms
Wall time: 845 ms

In [6]:
res


Out[6]:
defaultdict(int, {'1': 0, 'a': 318007, 'b': 196418, 'c': 0, 'd': 0})
--- Part Two --- As you head down the fire escape to the monorail, you notice it didn't start; register c needs to be initialized to the position of the ignition key. If you instead initialize register c to be 1, what value is now left in register a?

In [7]:
%%time 

assembunny = Assembunny()
assembunny.increase('c')
res = assembunny.execute(data)


CPU times: user 22.9 s, sys: 0 ns, total: 22.9 s
Wall time: 22.9 s

In [8]:
res


Out[8]:
defaultdict(int, {'a': 9227661, 'b': 5702887, 'c': 0, 'd': 0})