blob: bf84465a8b51501a1d14210835b7ec9de7ef7be7 (
plain)
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
|
#!/usr/bin/python
def solve_partn(partn, program):
if partn == 1:
regs = { "a" : 0, "b" : 0 }
else: # partn == 2
regs = { "a" : 1, "b" : 0 }
# "Parse" the input once up front, so we don't waste time
# doing this each iteration of a loop in the given program.
tokens = []
for line in program:
words = line.split()
words[1] = words[1].rstrip(",")
tokens.append(words)
# Main program execution loop
i = 0 # instruction pointer
while i < len(tokens):
op = tokens[i][0]
d1 = tokens[i][1]
# The "i += 1" is repeated for consistency and clarity
if op == "hlf":
regs[d1] = int(regs[d1] / 2)
i += 1
elif op == "tpl":
regs[d1] = regs[d1] * 3
i += 1
elif op == "inc":
regs[d1] = regs[d1] + 1
i += 1
elif op == "jmp":
i += int(d1)
elif op == "jie":
if regs[d1] % 2 == 0:
d2 = tokens[i][2]
i += int(d2)
else:
i += 1
elif op == "jio":
if regs[d1] == 1:
d2 = tokens[i][2]
i += int(d2)
else:
i += 1
return regs["b"]
def main():
# Read program's assembly code from input text file
with open("input.txt", "r") as f:
lines = f.read().splitlines()
print("Part 1 solution:", solve_partn(1, lines)) # 307 for me
print("Part 2 solution:", solve_partn(2, lines)) # 160 for me
if __name__ == "__main__":
main()
|