-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday06.py
47 lines (35 loc) · 1.12 KB
/
day06.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
import time
def load(file):
with open(file) as f:
return {(x, y): char for y, line in enumerate(f.read().split('\n'))
for x, char in enumerate(line)}
def run_guard_run(p, guard_pos, guard_dir):
distinct_pos, counter = set(), 0
while True:
(x, y), (dx, dy) = guard_pos, guard_dir
new_pos = x + dx, y + dy
if new_pos not in p: return distinct_pos
if counter > 500: return 'loop'
if p[new_pos] == '#':
guard_dir = -dy, dx
else:
guard_pos = new_pos
if new_pos in distinct_pos:
counter += 1
else:
distinct_pos.add(new_pos)
counter = 0
def solve(p):
part1 = part2 = 0
guard_pos = [pos for pos, char in p.items() if char == '^'][0]
guard_dir = (0, -1)
distinct_pos = run_guard_run(p, guard_pos, guard_dir)
part1 = len(distinct_pos | {guard_pos})
for pos in distinct_pos:
p[pos] = '#'
if run_guard_run(p, guard_pos, guard_dir) == 'loop': part2 += 1
p[pos] = '.'
return part1, part2
time_start = time.perf_counter()
print(f'Solution: {solve(load("day06.txt"))}')
print(f'Solved in {time.perf_counter()-time_start:.5f} Sec.')