diff options
author | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-18 14:53:36 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-18 14:53:36 +0000 |
commit | c5e1e087f53079e0a5125750bf4bed328d9b7d5c (patch) | |
tree | 20526290a2027b29c3e3a51cb2eed191c5aec932 | |
parent | b092a120b8c940f1eed2539f9b6d937d347541f9 (diff) | |
download | aoc2023-c5e1e087f53079e0a5125750bf4bed328d9b7d5c.tar.gz aoc2023-c5e1e087f53079e0a5125750bf4bed328d9b7d5c.tar.xz aoc2023-c5e1e087f53079e0a5125750bf4bed328d9b7d5c.zip |
day 18
-rw-r--r-- | 18.py | 43 |
1 files changed, 43 insertions, 0 deletions
@@ -0,0 +1,43 @@ +from collections.abc import Iterable +from dataclasses import dataclass +from itertools import islice +from sys import stdin +from typing import Self, Type + + +@dataclass +class Instruction: + direction: str + distance: int + + @classmethod + def from_str(cls: Type[Self], s: str) -> tuple[Self, Self]: + direction, distance, colour = s.split(" ") + colour = colour.strip("()#") + colour_dist = int(colour[:-1], 16) + colour_dir = "RDLU"[int(colour[-1], 16)] + return cls(direction, int(distance)), cls(colour_dir, colour_dist) + + +inp = [Instruction.from_str(l.rstrip("\n")) for l in stdin] + + +def solve(instructions: Iterable[Instruction]) -> int: + dirmap = {"U": (0, -1), "D": (0, 1), "L": (-1, 0), "R": (1, 0)} + pos = (0, 0) + area = 0 + border = 0 + for ins in instructions: + direction = dirmap[ins.direction] + newpos = ( + pos[0] + direction[0] * (ins.distance), + pos[1] + direction[1] * (ins.distance), + ) + area += pos[0] * newpos[1] - newpos[0] * pos[1] + border += ins.distance + pos = newpos + return (border + area) // 2 + 1 + + +print(solve(ins for ins, _ in inp)) +print(solve(ins for _, ins in inp)) |