I Heard You Like Registers

Part 1

What do registers look like?

b inc 5 if a > 1 a inc 1 if b < 5 c dec -10 if a >= 1 c inc -20 if c == 10

In [7]:
import csv

instructions = []
with open('input.txt', 'rt') as f_input:
    csv_reader = csv.reader(f_input, delimiter=' ')
    for line in csv_reader:
        reg = line[0]
        leap = int(line[2]) * ((line[1] == 'inc') + (line[1] == 'dec') * -1)
        cond = line[-3:]
        instructions.append((reg, leap, cond))

In [28]:
def apply_instructions(registers):
    for reg, leap, cond in instructions:
        bool_str = 'registers["{0}"]'.format(cond[0]) + ''.join(cond[1:])
        update_str = 'if {0}: registers["{1}"] += {2} '.format(bool_str, reg, leap)
        exec(update_str)

In [29]:
from collections import defaultdict
registers = defaultdict(int)
apply_instructions(registers)

In [34]:
max(registers.values())


Out[34]:
4647

Part 2


In [38]:
def yet_another_apply_instructions(registers):
    max_ever = 0
    for reg, leap, cond in instructions:
        bool_str = 'registers["{0}"]'.format(cond[0]) + ''.join(cond[1:])
        update_str = 'if {0}: registers["{1}"] += {2} '.format(bool_str, reg, leap)
        exec(update_str)
        m = max(registers.values())
        if m > max_ever: max_ever = m 
    return max_ever

In [39]:
registers = defaultdict(int)
max_ever = yet_another_apply_instructions(registers)
max_ever


Out[39]:
5590