-
Notifications
You must be signed in to change notification settings - Fork 0
/
aoc22.py
102 lines (90 loc) · 3.03 KB
/
aoc22.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
from collections import defaultdict
'''
s=""" ...#
.#..
#...
....
...#.......#
........#...
..#....#....
..........#.
...#....
.....#..
.#......
......#.
10R5L5R10L4R5L5"""
'''
with open("aoc_22_input.txt", "r") as f:
s = f.read().rstrip()
monkey_map = [row for row in s.split("\n\n")[0].split("\n")]
max_width = max(len(row) for row in monkey_map)
for i,row in enumerate(monkey_map):
if len(row) < max_width:
monkey_map[i] += " " * (max_width - len(row))
monkey_path = s.split("\n\n")[1]
curr = []
monkey_instr = []
for c in monkey_path:
if c.isnumeric():
curr.append(c)
else:
monkey_instr.append(int(''.join(curr)))
monkey_instr.append(c)
curr = []
if curr:
monkey_instr.append(int(''.join(curr)))
init_x, init_y, init_face = 0, monkey_map[0].index('.'), 0
curr_x, curr_y, curr_face = init_x, init_y, init_face
visited = defaultdict()
visited[(init_x, init_y)] = init_face
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def print_mmap(mmap, visited):
for i,r in enumerate(mmap):
for j,c in enumerate(r):
if (i,j) in visited:
if visited[(i,j)] == 0:
print('>', end="")
elif visited[(i,j)] == 1:
print('v', end="")
elif visited[(i,j)] == 2:
print('<', end="")
elif visited[(i,j)] == 3:
print('^', end="")
else:
print(c, end="")
print()
for inst in monkey_instr:
if inst == 'R':
curr_face += 1
curr_face %= 4
visited[(curr_x, curr_y)] = curr_face
elif inst == 'L':
curr_face -= 1
curr_face %= 4
visited[(curr_x, curr_y)] = curr_face
else:
for n in range(0, inst):
tx = (curr_x + dirs[curr_face][0]) % (len(monkey_map))
ty = (curr_y + dirs[curr_face][1]) % (max_width)
if monkey_map[tx][ty] == '#':
break
elif monkey_map[tx][ty] == ' ':
# wrap around
px, py = curr_x, curr_y
while monkey_map[tx][ty] == ' ':
curr_x, curr_y = tx, ty
tx = (curr_x + dirs[curr_face][0]) % (len(monkey_map))
ty = (curr_y + dirs[curr_face][1]) % (max_width )
if monkey_map[tx][ty] == '#':
curr_x, curr_y = px, py
break
else:
curr_x, curr_y = tx, ty
visited[(curr_x, curr_y)] = curr_face
else:
curr_x, curr_y = tx, ty
visited[(curr_x, curr_y)] = curr_face
#print_mmap(monkey_map, visited)
#print(f"X: {curr_x}\tY: {curr_y}\t Facing: {curr_face}")
pw = (1000 * (curr_x+1)) + (4 * (curr_y + 1)) + curr_face
print(f"Part 1: Final password on flat map: {pw}")