-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path21.py
91 lines (81 loc) · 2.94 KB
/
21.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
"""--- Day 21: Scrambled Letters and Hash ---"""
def swap(l, i, j):
l[i], l[j] = l[j], l[i]
return l
def move(l, i, j):
t = l.pop(i)
l.insert(j, t)
return l
def reverse(l, i, j):
sub = l[i:j][::-1]
return l[:i] + sub + l[j:]
def rotate_right(l, n):
i = n % len(l)
return l[-i:] + l[:-i]
def rotate_left(l, n):
i = n % len(l)
return l[i:] + l[:i]
with open("input/21.txt") as f:
password = list("abcdefgh")
for instruction in f:
cmd = instruction.split()
if cmd[0] == "swap":
if cmd[1] == "position":
password = swap(password, int(cmd[2]), int(cmd[5]))
else:
password = swap(password, password.index(cmd[2]), password.index(cmd[5]))
elif cmd[0] == "reverse":
password = reverse(password, int(cmd[2]), int(cmd[4]) + 1)
elif cmd[0] == "rotate":
if cmd[1] == "left":
password = rotate_left(password, int(cmd[2]))
elif cmd[1] == "right":
password = rotate_right(password, int(cmd[2]))
else:
rotations = password.index(cmd[6]) + 1
if rotations > 4:
rotations += 1
password = rotate_right(password, rotations)
elif cmd[0] == "move":
password = move(password, int(cmd[2]), int(cmd[5]))
print("".join(password))
with open("input/21.txt") as f:
instructions = f.read().split("\n")
instructions.reverse()
password = list("fbgdceah")
for instruction in instructions[1:]:
cmd = instruction.split()
if cmd[0] == "swap":
if cmd[1] == "position":
password = swap(password, int(cmd[5]), int(cmd[2]))
else:
password = swap(password, password.index(cmd[5]), password.index(cmd[2]))
elif cmd[0] == "reverse":
password = reverse(password, int(cmd[2]), int(cmd[4]) + 1)
elif cmd[0] == "rotate":
if cmd[1] == "left":
password = rotate_right(password, int(cmd[2]))
elif cmd[1] == "right":
password = rotate_left(password, int(cmd[2]))
else:
cur_pos = password.index(cmd[6])
if cur_pos == 0:
rotations = 1
elif cur_pos == 1:
rotations = 1
elif cur_pos == 2:
rotations = 6
elif cur_pos == 3:
rotations = 2
elif cur_pos == 4:
rotations = 7
elif cur_pos == 5:
rotations = 3
elif cur_pos == 6:
rotations = 0
elif cur_pos == 7:
rotations = 4
password = rotate_left(password, rotations)
elif cmd[0] == "move":
password = move(password, int(cmd[5]), int(cmd[2]))
print("".join(password))