-
Notifications
You must be signed in to change notification settings - Fork 0
/
aoc_utils.py
53 lines (38 loc) · 1.22 KB
/
aoc_utils.py
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
44
45
46
47
48
49
50
51
52
53
from collections.abc import Iterable
from typing import Generic, TypeVar
inf = float("inf")
adj4 = (-1j, 1, 1j, -1)
adj8 = (-1j, 1 - 1j, 1, 1 + 1j, 1j, 1j - 1, -1, 1j - 1)
dir_map = {"^": -1j, "v": 1j, ">": 1, "<": -1}
T = TypeVar("T")
K = TypeVar("K")
V = TypeVar("V")
class CostNode(tuple, Generic[K, T]):
cost: K
pos: T
def __new__(cls, cost: K, pos: T):
self = tuple.__new__(cls, (cost, pos))
self.cost = cost
self.pos = pos
return self
def __lt__(self, other):
return self.cost < other.cost
def complex_grid(
input: Iterable[Iterable[T]], filter: Iterable[T] | None = None
) -> dict[complex, T]:
return {
i + j * 1j: c
for j, line in enumerate(input)
for i, c in enumerate(line)
if not filter or c in filter
}
def grid_find(grid: str, target: str) -> complex:
for j, line in enumerate(grid.split("\n")):
for i, c in enumerate(line):
if c == target:
return complex(i, j)
return complex(float("inf"), float("inf"))
def find_key_by_value(d: dict[K, V], v: V) -> K:
return list(d.keys())[list(d.values()).index(v)]
def ij(x: complex) -> tuple[int, int]:
return int(x.real), int(x.imag)