Day 10 - Advent of Code 2022

Working solutions for the day 10 puzzles.

Part One

""" day_10_01.py """

# usage: python3 day_10_01.py < input

import sys


class Device():
    """ simulate puzzle device """
    def __init__(self, program):
        self.program = program.splitlines()
        self.x = None
        self.cycle = None
        self.pc = None
        self.solution = None

    def step(self, breaks):
        """ execute current line """
        if self.cycle + 1 in breaks:
            self.solution += (self.cycle + 1) * self.x
        line = self.program[self.pc]
        if line == 'noop':
            self.cycle += 1
        elif line.startswith('addx '):
            if self.cycle + 2 in breaks:
                self.solution += (self.cycle + 2) * self.x
            _, value = line.split()
            self.x += int(value)
            self.cycle += 2
        self.pc += 1

    def run(self, breaks):
        """ execute program """
        self.x = 1
        self.cycle = 0
        self.pc = 0
        self.solution = 0
        while self.pc < len(self.program):
            self.step(breaks)


handheld = Device(sys.stdin.read())
handheld.run([20, 60, 100, 140, 180, 220])
print(handheld.solution)

Part Two

""" day_10_02.py """

# usage: python3 day_10_02.py < input

import sys


class Device():
    """ simulate puzzle device """
    def __init__(self, program):
        self.program = program.splitlines()
        self.x = None
        self.cycle = None
        self.pc = None
        self.solution = None

    def sprite(self, cycle):
        """ check if sprite visible when pixel is drawn """
        y, x = divmod(cycle, 40)
        if x in [self.x - 1, self.x, self.x + 1]:
            self.solution[y][x] = '#'

    def step(self):
        """ execute current line """
        self.sprite(self.cycle)
        line = self.program[self.pc]
        if line == 'noop':
            self.cycle += 1
        elif line.startswith('addx '):
            self.sprite(self.cycle + 1)
            _, value = line.split()
            self.x += int(value)
            self.cycle += 2
        self.pc += 1

    def run(self):
        """ execute program """
        self.x = 1
        self.cycle = 0
        self.pc = 0
        self.solution = [['.' for _ in range(40)] for _ in range(6)]
        while self.pc < len(self.program):
            self.step()

    def crt(self):
        """ render solution as CRT """
        output = []
        for line in self.solution:
            output += [''.join(line)]
        return '\n'.join(output)


handheld = Device(sys.stdin.read())
handheld.run()
print(handheld.crt())