-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.py
95 lines (71 loc) · 1.99 KB
/
day2.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
# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime
import os
top_dir = os.path.dirname(os.path.abspath(__file__)) + "/../../"
def get_instructions_from_file(file_path=top_dir + "resources/year2016_day2_input.txt"):
with open(file_path) as f:
return [l.strip() for l in f]
def dict_from_grid(grid):
return {
(i, j): val
for i, line in enumerate(grid)
for j, val in enumerate(line)
if val != " "
}
directions = {
"U": (-1, 0),
"D": (1, 0),
"R": (0, 1),
"L": (0, -1),
}
def get_neighbours(point):
x, y = point
return {l: (x + dx, y + dy) for l, (dx, dy) in directions.items()}
def get_graph_from_points(points):
graph = dict()
for p in points:
graph[p] = {l: p2 for l, p2 in get_neighbours(p).items() if p2 in points}
return graph
def follow_instruction(graph, instruction, start):
p = start
for ins in instruction:
p = graph[p].get(ins, p)
return p
def follow_instructions(grid, instructions, start):
p = start
points = dict_from_grid(grid)
graph = get_graph_from_points(points)
ret = []
for ins in instructions:
p = follow_instruction(graph, ins, p)
ret.append(points[p])
return "".join(ret)
keypad = ["123", "456", "789"]
start = (1, 1)
keypad2 = [
" 1",
" 234",
"56789",
" ABC",
" D",
]
start2 = (2, 0)
def run_tests():
instructions = [
"ULL",
"RRDDD",
"LURDL",
"UUUUD",
]
assert follow_instructions(keypad, instructions, start) == "1985"
assert follow_instructions(keypad2, instructions, start2) == "5DB3"
def get_solutions():
instructions = get_instructions_from_file()
print(follow_instructions(keypad, instructions, start) == "53255")
print(follow_instructions(keypad2, instructions, start2) == "7423A")
if __name__ == "__main__":
begin = datetime.datetime.now()
run_tests()
get_solutions()
end = datetime.datetime.now()
print(end - begin)