summaryrefslogtreecommitdiffstats
path: root/18.py
blob: a294ee2c991829b57fbcdc850a3a946f6f11517f (plain)
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
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))