-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday6.py
118 lines (84 loc) · 2.55 KB
/
day6.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# Advent of Code 2024, Day 6
# (c) blu3r4y
from aocd.models import Puzzle
from funcy import print_calls, print_durations
from tqdm.auto import tqdm
GUARD = "^"
WALL = "#"
@print_calls
@print_durations(unit="ms")
def part1(data):
walls, guard, limits = data
visited = set()
heading = -1j
while within_bounds(guard, limits):
visited.add(guard)
while guard + heading in walls:
heading *= 1j # turn right
guard += heading
return len(visited)
@print_calls
@print_durations(unit="ms")
def part2(data):
walls, guard, limits = data
width, height = limits
obstructions = 0
pbar = tqdm(total=width * height - len(walls) - 1)
for r in range(width):
for c in range(height):
cell = complex(c, r)
if cell == guard or cell in walls:
continue
if is_guard_looping(walls | {cell}, guard, limits):
obstructions += 1
pbar.update(1)
return obstructions
def within_bounds(pos, limits):
height, width = limits
return 0 <= pos.imag < height and 0 <= pos.real < width
def is_guard_looping(walls, guard, limits):
visited = []
heading = -1j
while within_bounds(guard, limits):
# cycle-checking is costly, so only do it sometimes
if len(visited) % 10_000 == 0:
if detect_cycle(visited):
return True
visited.append(guard)
while guard + heading in walls:
heading *= 1j # turn right
guard += heading
# out of bounds, no cycle
return False
def detect_cycle(visited):
if len(visited) < 2:
return False
# Floyd's Tortoise and Hare algorithm
tortoise, hare = 0, 0
while True:
if hare + 1 >= len(visited) or hare + 2 >= len(visited):
return False
tortoise += 1
hare += 2
if visited[tortoise] == visited[hare]:
return True
def load(data):
walls, guard = set(), None
rows = data.splitlines()
for r, row in enumerate(data.splitlines()):
for c, cell in enumerate(row):
pos = complex(c, r)
if cell == WALL:
walls.add(pos)
elif cell == GUARD:
guard = pos
limits = len(rows), len(rows[0])
return walls, guard, limits
if __name__ == "__main__":
puzzle = Puzzle(year=2024, day=6)
ans1 = part1(load(puzzle.input_data))
assert ans1 == 5242
puzzle.answer_a = ans1
ans2 = part2(load(puzzle.input_data))
assert ans2 == 1424
puzzle.answer_b = ans2