advent-of-code/src/holt59/aoc/2021/day2.py
Mikaël Capelle 1b4dd32898
Some checks failed
continuous-integration/drone/pr Build is failing
continuous-integration/drone/push Build is failing
Refactor 2021 for new UI.
2024-12-08 14:03:34 +01:00

39 lines
1.1 KiB
Python

from math import prod
from typing import Any, Iterator, Literal, TypeAlias, cast
from ..base import BaseSolver
Command: TypeAlias = Literal["forward", "up", "down"]
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
commands: list[tuple[Command, int]] = [
(cast(Command, (p := line.split())[0]), int(p[1])) for line in lines
]
def depth_and_position(use_aim: bool):
aim, pos, depth = 0, 0, 0
for command, value in commands:
d_depth = 0
match command:
case "forward":
pos += value
depth += value * aim
case "up":
d_depth = -value
case "down":
d_depth = value
if use_aim:
aim += d_depth
else:
depth += value
return depth, pos
yield prod(depth_and_position(False))
yield prod(depth_and_position(True))