#!/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()