Chellenge 12

Challenge 12.1


In [1]:
myinput = '/home/fmuinos/projects/adventofcode/2016/ferran/inputs/input12.txt'

In [2]:
from collections import defaultdict

def parse_comm_dict(myinput):
    with open(myinput, 'rt') as f:
        i = 1
        comm_dict = {}
        for line in f:
            comm = line[:3]
            args = []
            args.append(line[4:].rstrip().split(' ')[0])
            try:
                args.append(line[4:].rstrip().split(' ')[1])
            except:
                pass
            comm_dict[i] = (comm, args)
            i += 1
    return comm_dict

class AssembunnyInterpreter(object):
    
    def __init__(self, commands):
        self.commands = commands
        self.registry = {'a': 0, 'b': 0, 'c': 0, 'd': 0}
        self.pointer = 1
    
    def update(self):
        comm = self.commands[self.pointer][0]
        args = self.commands[self.pointer][1]
        if comm == 'cpy':
            if args[0] in self.registry:
                self.registry[args[1]] = self.registry[args[0]]
            else:
                self.registry[args[1]] = int(args[0])
            self.pointer += 1
        elif comm == 'inc':
            self.registry[args[0]] += 1
            self.pointer += 1
        elif comm == 'dec':
            self.registry[args[0]] -= 1
            self.pointer += 1
        elif comm == 'jnz':
            if args[0] in self.registry:
                if self.registry[args[0]] != 0:
                    self.pointer = self.pointer + int(args[1])
                else:
                    self.pointer += 1
            elif int(args[0]) != 0:
                self.pointer = self.pointer + int(args[1])
            else:
                self.pointer += 1

In [167]:
commands = parse_comm_dict(myinput)
interpreter = AssembunnyInterpreter(commands)
while interpreter.pointer in command:
    interpreter.update()
interpreter.registry


Out[167]:
{'a': 318003, 'b': 196418, 'c': 0, 'd': 0}

Challenge 12.2


In [169]:
commands = parse_comm_dict(myinput)
interpreter = AssembunnyInterpreter(commands)
interpreter.registry['c'] = 1
while interpreter.pointer in command:
    interpreter.update()
interpreter.registry


Out[169]:
{'a': 9227657, 'b': 5702887, 'c': 0, 'd': 0}