Advent of Code: Day 19

For Day 19, the challenge is to follow a map, recording letters that are passed on the route.

import time

UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)


with open("input.txt", "r") as o:
    m = o.readlines()

y = 0
x = m[y].index("|")
direction = DOWN


path = []
steps = 0

def read(m, x, y):
    if len(m) <= y or len(m[y]) <= x:
        return " "
    return m[y][x]

def peek(m, x, y, direction):
    x += direction[0]
    y += direction[1]
    return read(m, x, y)


while True:
    if read(m, x, y).isalpha():
        path.append(m[y][x])
    elif read(m, x, y) == " ":
        break
    elif m[y][x] == "+" and peek(m, x, y, direction) == " ":
        # We need to turn
        if direction[0] == 0:
            # Moving up or down
            possible_directions = [LEFT, RIGHT]
        else:
            # Moving left or right
            possible_directions = [UP, DOWN]

        direction = None
        for d in possible_directions:
            if not peek(m, x, y, d) == " ":
                direction = d

        if not direction:
            print "Done"
            break

    x += direction[0]
    y += direction[1]
    steps += 1

print "Part 1", "".join(path)
print "Part 2", steps

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

Show Comments

Get the latest posts delivered right to your inbox.