Advent of Code: Day 25

For Day 25, the challenge is to implement a turing machine simulator.

My Python solution is:

states = {}

current_state = None
current_rule = None

def enter_state(line):
    global current_state
    current_state = line.rsplit(" ", 1)[-1][:-1]
    if current_state not in states:
        states[current_state] = {}

def enter_rule(line):
    global current_rule
    current_rule = int(line.rsplit(" ", 1)[-1][:-1])
    if current_rule not in states[current_state]:
        states[current_state][current_rule] = []

def add_instruction(line):
    if line.startswith("- Write the value"):
        states[current_state][current_rule].append(("write", int(line.rsplit(" ", 1)[1][:-1])))
    elif line.startswith("- Move one slot"):
        if line.endswith("left."):
            states[current_state][current_rule].append(("move", -1))
        elif line.endswith("right."):
            states[current_state][current_rule].append(("move", 1))
            print "Unknown direction"
    elif line.startswith("- Continue with state"):
        states[current_state][current_rule].append(("change", line.rsplit(" ", 1)[1][:-1]))
        print "Unknown instruction", line

with open("input.txt", "r") as o:
    lines = o.readlines()
    start_state = lines[0].strip().rsplit(" ", 1)[1][:-1]
    checksum_steps = int(lines[1].split(" ")[-2])
    for l in lines[2:]:
        line = l.strip()
        if line.startswith("In state"):
        elif line.startswith("If the current value is"):
        elif line.startswith("- "):

tape = {}
ptr = 0

current_state = start_state
for i in range(checksum_steps):
    current_value = tape.get(ptr, 0)
    for step in states[current_state][current_value]:
        if step[0] == "write":
            tape[ptr] = step[1]
        elif step[0] == "move":
            ptr += step[1]
        elif step[0] == "change":
            current_state = step[1]
            print "Unknown command"

print len([i for i in tape.values() if i == 1])

And that's it! I really enjoyed completing Advent of Code this year. A lot of really fun little puzzles to fill in my morning.

If you haven't taken part yourself, you should know that all of the puzzles are still available. You should give it a go!.

Show Comments

Get the latest posts delivered right to your inbox.