Day 6 - Advent of Code 2015

Working solutions for the day 6 puzzles.

Part One

""" day_06_01.py """

# usage: python3 day_06_01.py < input


import sys


def parse(data):
    """ generate instructions """
    def convert(text):
        """ convert text "x,y" to integer tuple (x, y) """
        return tuple(int(i) for i in text.split(','))

    def rectangle(topleft, bottomright):
        """ calculate points of rectangle """
        x1, y1 = convert(topleft)
        x2, y2 = convert(bottomright)
        return set((x, y) for y in range(y1, y2 + 1)
                   for x in range(x1, x2 + 1))

    def prepare(text):
        """ prepare for processing """
        command, top_left, _, bottom_right = text.replace('turn ', '').split()
        items = rectangle(top_left, bottom_right)
        return command, items

    return (prepare(instruction) for instruction in data.splitlines())


display = set()
for action, lights in parse(sys.stdin.read()):
    if action == 'on':
        display = display.union(lights)
    elif action == 'off':
        display = display.difference(lights)
    elif action == 'toggle':
        display = display.symmetric_difference(lights)
print(len(display))

Part Two

""" day_06_02.py """

# usage: python3 day_06_02.py < input


import sys


def parse(data):
    """ generate instructions """
    def convert(text):
        """ convert text "x,y" to integer tuple (x, y) """
        return tuple(int(i) for i in text.split(','))

    def rectangle(topleft, bottomright):
        """ calculate points of rectangle """
        x1, y1 = convert(topleft)
        x2, y2 = convert(bottomright)
        return set((x, y) for y in range(y1, y2 + 1)
                   for x in range(x1, x2 + 1))

    def prepare(text):
        """ prepare for processing """
        command, top_left, _, bottom_right = text.replace('turn ', '').split()
        items = rectangle(top_left, bottom_right)
        return command, items

    return (prepare(instruction) for instruction in data.splitlines())


display = {}
for action, lights in parse(sys.stdin.read()):
    if action == 'on':
        for light in lights:
            display[light] = display.get(light, 0) + 1
    elif action == 'off':
        for light in lights:
            display[light] = max(0, display.get(light, 0) - 1)
    elif action == 'toggle':
        for light in lights:
            display[light] = display.get(light, 0) + 2
print(sum(display.values()))