diff options
Diffstat (limited to '23')
-rw-r--r-- | 23/input.txt | 47 | ||||
-rwxr-xr-x | 23/main.py | 65 | ||||
-rwxr-xr-x | 23/test.py | 22 |
3 files changed, 134 insertions, 0 deletions
diff --git a/23/input.txt b/23/input.txt new file mode 100644 index 0000000..a2b735a --- /dev/null +++ b/23/input.txt @@ -0,0 +1,47 @@ +jio a, +18 +inc a +tpl a +inc a +tpl a +tpl a +tpl a +inc a +tpl a +inc a +tpl a +inc a +inc a +tpl a +tpl a +tpl a +inc a +jmp +22 +tpl a +inc a +tpl a +inc a +inc a +tpl a +inc a +tpl a +inc a +inc a +tpl a +tpl a +inc a +inc a +tpl a +inc a +inc a +tpl a +inc a +inc a +tpl a +jio a, +8 +inc b +jie a, +4 +tpl a +inc a +jmp +2 +hlf a +jmp -7 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() diff --git a/23/test.py b/23/test.py new file mode 100755 index 0000000..19dad35 --- /dev/null +++ b/23/test.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +import unittest + +import main + + + +class ExamplesPart1(unittest.TestCase): + def test_example1(self): + prog = [ + "inc b", + "jio b, +2", + "tpl b", + "inc b" + ] + self.assertEqual(main.solve_partn(1, prog), 2) + + + +if __name__ == "__main__": + unittest.main() |