-
Notifications
You must be signed in to change notification settings - Fork 0
/
day10.py
77 lines (59 loc) · 1.7 KB
/
day10.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Advent of Code 2023, Day 10: Pipe Maze.
"""
import sys
from itertools import pairwise
from typing import TextIO
from aoc_2023.grid import Grid, NORTH, EAST, SOUTH, WEST
START_DIRECTIONS = {
NORTH: "|F7",
SOUTH: "|JL",
EAST: "-J7",
WEST: "-FL",
}
DIRECTIONS = {
"-": {WEST: WEST, EAST: EAST},
"|": {NORTH: NORTH, SOUTH: SOUTH},
"L": {WEST: NORTH, SOUTH: EAST},
"J": {EAST: NORTH, SOUTH: WEST},
"7": {EAST: SOUTH, NORTH: WEST},
"F": {NORTH: EAST, WEST: SOUTH},
}
def find_loop(grid: Grid) -> list[complex]:
start = next(coord for coord, cell in grid.items() if cell == "S")
direction = next(
d for d, s in START_DIRECTIONS.items() if grid.get(start + d, "?") in s
)
position = start + direction
loop = [start]
while position != start:
loop.append(position)
symbol = grid[position]
direction = DIRECTIONS[symbol][direction]
position = position + direction
return loop
def part_one(file: TextIO) -> int:
grid = Grid.from_ascii_grid(file)
loop = find_loop(grid)
return len(loop) // 2
def part_two(file: TextIO) -> int:
grid = Grid.from_ascii_grid(file)
loop = find_loop(grid)
area = (
abs(
sum(
p1.real * p2.imag - p2.real * p1.imag
for p1, p2 in pairwise([*loop, loop[0]])
)
)
// 2
)
return area - len(loop) // 2 + 1
def main():
filename = sys.argv[0].replace(".py", ".txt")
with open(filename, encoding="utf-8") as file:
print("Part one:", part_one(file))
with open(filename, encoding="utf-8") as file:
print("Part two:", part_two(file))
if __name__ == "__main__":
main()