-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday6.py
More file actions
executable file
·79 lines (51 loc) · 1.47 KB
/
day6.py
File metadata and controls
executable file
·79 lines (51 loc) · 1.47 KB
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
78
79
import re
from aoc_utils import * # type: ignore
from aocd import get_data
data = get_data(year=2024, day=6, block=True)
def parse(data):
grid = Grid([[c for c in line] for line in data.splitlines()])
guard = None
for yx, c in grid.row_major_with_index():
if c == "^":
guard = yx
break
assert guard
grid[guard] = "."
return grid, guard
def simulate(grid, guard):
direction = Direction.NORTH
visited = set([(guard, direction)])
while True:
y, x = guard
dy, dx = direction.value
yy, xx = y + dy, x + dx
yyxx = (yy, xx)
if yyxx not in grid:
return visited
if (yyxx, direction) in visited:
return None
if grid[yyxx] != ".":
direction = direction.rotate(cardinal=True)
else:
guard = yyxx
visited.add((yyxx, direction))
def part_one(data):
grid, starting = parse(data)
visited = set(p for p, _ in simulate(grid, starting))
return len(visited)
def part_two(data):
grid, starting = parse(data)
visited = set(p for p, _ in simulate(grid, starting))
assert visited
looped = 0
for yx in visited:
if grid[yx] != "." or yx == starting:
continue
grid[yx] = "#"
visited = simulate(grid, starting)
grid[yx] = "."
if visited is None:
looped += 1
return looped
print(part_one(data))
print(part_two(data))