1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
# -*- coding: utf-8 -*-
from abc import ABC
from functools import lru_cache
from typing import Iterator, List, Dict, Any
from aoc import BaseAssignment
class Assignment(BaseAssignment, ABC):
def __init__(self, path):
super().__init__(path)
self.x_history = {1: 1}
def parse_instructions(self, instructions: Iterator[str]) -> Iterator[int]:
x = 1
for instruction in instructions:
instruction, *args = instruction.split(" ")
yield x
if instruction != "noop":
yield x
x += int(*args)
class AssignmentOne(Assignment):
example_result = 13140
def run(self, input: Iterator) -> int:
return sum(
[
cycle * x
for cycle, x in enumerate(self.parse_instructions(input), start=1)
if cycle in {20, 60, 100, 140, 180, 220}
]
)
class AssignmentTwo(Assignment):
example_result = (
"██ ██ ██ ██ ██ ██ ██ ██ ██ ██ \n"
"███ ███ ███ ███ ███ ███ ███ \n"
"████ ████ ████ ████ ████ \n"
"█████ █████ █████ █████ \n"
"██████ ██████ ██████ ████\n"
"███████ ███████ ███████ "
)
def render_pixel(self, row: int, col: int, instructions: List[str]):
cycle = row * 40 + col
x_register = self.x_after(cycle, instructions)
if col in [x_register - 1, x_register, x_register + 1]:
return "#"
return "."
def run(self, input: Iterator) -> str:
rows = []
row = []
for cycle, x in enumerate(self.parse_instructions(instructions=input), start=1):
col = (cycle - 1) % 40
row.append("█" if col in {x - 1, x, x + 1} else " ")
if cycle % 40 == 0:
rows.append(row)
row = []
return "\n".join("".join(row) for row in rows)
|