From c5e1e087f53079e0a5125750bf4bed328d9b7d5c Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 18 Dec 2023 14:53:36 +0000 Subject: day 18 --- 18.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 18.py (limited to '18.py') diff --git a/18.py b/18.py new file mode 100644 index 0000000..a294ee2 --- /dev/null +++ b/18.py @@ -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)) -- cgit v1.2.3-54-g00ecf