Day 1 - Advent of Code 2016

Working solutions for the day 1 puzzles.

Part One

""" day_01_01.py """

# usage: python3 day_01_01.py < input

import sys


def sequence():
    """ issue next item in sequence """
    for i in sys.stdin.read().strip().split(', '):
        yield i


heading = 0
position = [0, 0]

for item in sequence():
    if item[0] == 'L':
        heading = (heading - 1) % 4
    else:
        heading = (heading + 1) % 4

    steps = int(item[1:])

    match heading:
        case 0:
            position[1] += steps
        case 1:
            position[0] += steps
        case 2:
            position[1] -= steps
        case 3:
            position[0] -= steps

print(abs(position[0]) + abs(position[1]))

Part Two

""" day_01_02.py """

# usage: python3 day_01_02.py < input

import sys


def sequence():
    """ issue next item in sequence """
    for i in sys.stdin.read().strip().split(', '):
        yield i


def step(hdg, pos):
    """ step one unit from position in direction of heading """
    x, y = pos
    match hdg:
        case 0:
            return (x, y + 1)
        case 1:
            return (x + 1, y)
        case 2:
            return (x, y - 1)
        case 3:
            return (x - 1, y)


heading = 0
position = (0, 0)
trail = [position]
second_visit = False

for item in sequence():
    if item[0] == 'L':
        heading = (heading - 1) % 4
    else:
        heading = (heading + 1) % 4

    for _ in range(int(item[1:])):
        position = step(heading, position)
        if position in trail:
            second_visit = True
            break
        trail.append(position)

    if second_visit:
        break

print(abs(position[0]) + abs(position[1]))