-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathday20.py
70 lines (54 loc) · 1.73 KB
/
day20.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
from collections import defaultdict
D = {'N': (0, -1), 'E': (1, 0), 'S': (0, 1), 'W': (-1, 0)}
def parse_input(filename: str) -> str:
return open(filename).read().strip()[1: -1]
def part1(path: str) -> int:
positions = []
distances = defaultdict(int)
x, y = 0, 0
prev_x, prev_y = x, y
for ch in path:
if ch == '(':
positions.append((x, y))
elif ch == ')':
x, y = positions.pop()
elif ch == '|':
x, y = positions[-1]
else:
dx, dy = D[ch]
x += dx
y += dy
if distances[(x, y)] != 0:
distances[(x, y)] = min(distances[(x, y)], distances[(prev_x, prev_y)] + 1)
else:
distances[(x, y)] = distances[(prev_x, prev_y)] + 1
prev_x, prev_y = x, y
return max(distances.values())
def part2(path: str) -> int:
positions = []
distances = defaultdict(int)
x, y = 0, 0
prev_x, prev_y = x, y
for ch in path:
if ch == '(':
positions.append((x, y))
elif ch == ')':
x, y = positions.pop()
elif ch == '|':
x, y = positions[-1]
else:
dx, dy = D[ch]
x += dx
y += dy
if distances[(x, y)] != 0:
distances[(x, y)] = min(distances[(x, y)], distances[(prev_x, prev_y)] + 1)
else:
distances[(x, y)] = distances[(prev_x, prev_y)] + 1
prev_x, prev_y = x, y
return len([distance for distance in distances if distances[distance] >= 1000])
def main():
path = parse_input('input/day20.txt')
print(f'Part 1: {part1(path)}')
print(f'Part 2: {part2(path)}')
if __name__ == "__main__":
main()