-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday25.py
124 lines (101 loc) · 2.91 KB
/
day25.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
119
120
121
122
123
124
# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime
import os
import collections
import itertools
top_dir = os.path.dirname(os.path.abspath(__file__)) + "/../../"
def get_sea_from_file(file_path=top_dir + "resources/year2021_day25_input.txt"):
with open(file_path) as f:
return [l.strip() for l in f]
GridInfo = collections.namedtuple(
"GridInfo", ["height", "width", "east_facing", "south_facing"]
)
def get_info_from_sea_grid(sea_grid):
east_facing = set() # ">"
south_facing = set() # "v"
height = len(sea_grid)
width = len(sea_grid[0])
for i, line in enumerate(sea_grid):
assert len(line) == width
for j, val in enumerate(line):
p = (i, j)
if val == "v":
south_facing.add(p)
elif val == ">":
east_facing.add(p)
else:
assert val == "."
return GridInfo(height, width, east_facing, south_facing)
def show_sea(grid_info):
def cucumber(p):
return (
">"
if p in grid_info.east_facing
else "v"
if p in grid_info.south_facing
else "."
)
for i in range(grid_info.height):
print("".join(cucumber((i, j)) for j in range(grid_info.width)))
print()
def next_step(grid_info):
# Move East-facing herd
adjacent = [
((i, j), (i, (j + 1) % grid_info.width)) for i, j in grid_info.east_facing
]
east2 = set(
p1 if (p2 in grid_info.east_facing or p2 in grid_info.south_facing) else p2
for p1, p2 in adjacent
)
# Move South-facing herd
adjacent = [
((i, j), ((i + 1) % grid_info.height, j)) for i, j in grid_info.south_facing
]
south2 = set(
p1 if (p2 in east2 or p2 in grid_info.south_facing) else p2
for p1, p2 in adjacent
)
return GridInfo(grid_info.height, grid_info.width, east2, south2)
def next_steps(info):
for i in itertools.count(start=1):
info2 = next_step(info)
if info == info2:
return i
info = info2
def run_tests():
sea = [
"...>...",
".......",
"......>",
"v.....>",
"......>",
".......",
"..vvv..",
]
info = get_info_from_sea_grid(sea)
info = next_step(info)
sea = [
"v...>>.vv>",
".vv>>.vv..",
">>.>v>...v",
">>v>>.>.v.",
"v>v.vv.v..",
">.>>..v...",
".vv..>.>v.",
"v.v..>>v.v",
"....v..v.>",
]
info = get_info_from_sea_grid(sea)
info = next_step(info)
info = get_info_from_sea_grid(sea)
assert next_steps(info) == 58
def get_solutions():
sea = get_sea_from_file()
info = get_info_from_sea_grid(sea)
print(next_steps(info) == 523)
if __name__ == "__main__":
begin = datetime.datetime.now()
run_tests()
get_solutions()
end = datetime.datetime.now()
print(end - begin)