From 68615a9ad2c942254135cffb00cf25a84a3b1356 Mon Sep 17 00:00:00 2001 From: Prefetch Date: Sat, 31 Dec 2022 22:21:39 +0100 Subject: Initial commit --- 23/main.py | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100755 23/main.py (limited to '23/main.py') 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() -- cgit v1.2.3