summaryrefslogtreecommitdiff
path: root/23/main.py
diff options
context:
space:
mode:
authorPrefetch2022-12-31 22:21:39 +0100
committerPrefetch2022-12-31 22:21:39 +0100
commit68615a9ad2c942254135cffb00cf25a84a3b1356 (patch)
tree1ed3131f673207b2ef0bdaee3ee98bb68d6640ca /23/main.py
Initial commit
Diffstat (limited to '23/main.py')
-rwxr-xr-x23/main.py65
1 files changed, 65 insertions, 0 deletions
diff --git a/23/main.py b/23/main.py
new file mode 100755
index 0000000..bf84465
--- /dev/null
+++ b/23/main.py
@@ -0,0 +1,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()