Advent of Code: Day 8

For Day 8, the challenge is to execute some simple instructions to manipulate registers, and then print some basic facts about the state of the registers. My Python solution is below:

registers = {}
highest_value = -99999

def check_condition(condition):
    register, command, value = condition.split(" ")
    value = int(value)
    if command == ">":
        return registers.get(register, 0) > value
    elif command == ">=":
        return registers.get(register, 0) >= value
    elif command == "<":
        return registers.get(register, 0) < value
    elif command == "<=":
        return registers.get(register, 0) <= value
    elif command == "==":
        return registers.get(register, 0) == value
    elif command == "!=":
        return registers.get(register, 0) != value
    else:
        raise Exception("Unknown command: %s" % command)

def execute_instruction(instruction):
    global highest_value
    register, command, value = instruction.split(" ")
    value = int(value)
    if command == "inc":
        registers[register] = registers.get(register, 0) + value
    elif command == "dec":
        registers[register] = registers.get(register, 0) - value
    else:
        raise Exception("Unknown command: %s" % command)

    if registers[register] > highest_value:
        highest_value = registers[register]

with open("input.txt", "r") as i:
    for line in i:
        line = line.strip()
        instruction, condition = line.split(" if ")
        if check_condition(condition):
            execute_instruction(instruction)

print "Part 1: " + str(max(registers.values()))
print "Part 2: " + str(highest_value)

This is very simple, just split up the instruction and condition by spaces - and some if conditions to figure out what to do.

Advent of Code runs every day up to Christmas, you should join in!.

Show Comments

Get the latest posts delivered right to your inbox.