From 9285442688749d1cdd9dcc12ea6113fbc59b96bc Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 10 Dec 2022 10:28:46 +0100 Subject: [PATCH] 2022: d10: ex1: add solution --- 2022/d10/ex1/ex1.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100755 2022/d10/ex1/ex1.py diff --git a/2022/d10/ex1/ex1.py b/2022/d10/ex1/ex1.py new file mode 100755 index 0000000..20f8fd5 --- /dev/null +++ b/2022/d10/ex1/ex1.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python + +import dataclasses +import sys +from collections.abc import Iterable, Iterator + + +@dataclasses.dataclass +class CPU: + x: int = dataclasses.field(default=1, init=False) + cycle: int = dataclasses.field(default=0, init=False) + + def execute(self, instructions: Iterable[str]) -> Iterator[int]: + for instr in instructions: + yield from self.execute_once(instr) + + def execute_once(self, instruction: str) -> Iterator[int]: + if instruction == "noop": + yield from self.__do_cycle() + else: + assert instruction.startswith("addx") + yield from self.__do_cycle(2) + self.x += int(instruction.split()[1]) + + def __do_cycle(self, cycles: int = 1) -> Iterator[int]: + for _ in range(cycles): + self.cycle += 1 + yield self.cycle + + +def solve(input: list[str]) -> int: + cpu = CPU() + return sum(cycle * cpu.x for cycle in cpu.execute(input) if (cycle % 40) == 20) + + +def main() -> None: + input = sys.stdin.read().splitlines() + print(solve(input)) + + +if __name__ == "__main__": + main()