Advent of Code: Day 22

For Day 22, the challenge is to follow some rules to spread a virus through an infinite grid.

import copy
marked = {}

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

CLEAN = 0
WEAKENED = 1
INFECTED = 2
FLAGGED = 3

def turn(current, turn_direction):
    if current == UP:
        return turn_direction
    elif current == DOWN and turn_direction == LEFT:
        return RIGHT
    elif current == DOWN:
        return LEFT
    elif current == LEFT and turn_direction == LEFT:
        return DOWN
    elif current == LEFT:
        return UP
    elif turn_direction == LEFT:
        return UP
    return DOWN


with open("input.txt", "r") as o:
    lines = [l.strip() for l in o]
    for y in range(len(lines)):
        for x in range(len(lines[0])):
            if lines[y][x] == "#":
                marked[(x, y)] = INFECTED

    x = len(lines[0]) / 2
    y = len(lines) / 2

def part1_rules(direction, marked, x, y):
    direction = turn(direction, RIGHT if marked.get((x, y)) == INFECTED else LEFT)

    state = marked.get((x, y), CLEAN)
    if state == INFECTED:
        state = CLEAN
    else:
        state = INFECTED

    marked[(x, y)] = state

    return direction

def part2_rules(direction, marked, x, y):
    state = marked.get((x, y), CLEAN)

    if state == CLEAN:
        direction = turn(direction, LEFT)
        state = WEAKENED
    elif state == WEAKENED:
        state = INFECTED
    elif state == INFECTED:
        direction = turn(direction, RIGHT)
        state = FLAGGED
    else:
        direction = turn(turn(direction, LEFT), LEFT)
        state = CLEAN

    marked[(x, y)] = state

    return direction

def run(iterations, marked, x, y, rules=part1_rules):
    marked = copy.deepcopy(marked)
    direction = UP
    caused_infection_count = 0
    for i in range(iterations):
        direction = rules(direction, marked, x, y)
        if marked[(x, y)] == INFECTED:
            caused_infection_count += 1
        x += direction[0]
        y += direction[1]
    return caused_infection_count

print "Part 1", run(10000, marked, x, y)
print "Part 2", run(10000000, marked, x, y, part2_rules)

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

Show Comments

Get the latest posts delivered right to your inbox.