#/usr/bin/env python program = [] with open("/home/login/bin/advent17/input23.txt") as f: for instruction_line in f: program.append(instruction_line.split()) program_length = len(program) registers = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0, 'f': 0, 'g': 0, 'h': 0} instruction_counter = 0 def set_op(x, y): global registers if y in registers: registers[x] = registers[y] else: registers[x] = int(y) def sub_op(x, y): global registers if y in registers: registers[x] -= registers[y] else: registers[x] -= int(y) mul_count = 0 def mul_op(x, y): global registers, mul_count if y in registers: registers[x] *= registers[y] else: registers[x] *= int(y) mul_count+=1 def jnz_op(x, y): global registers, instruction_counter test_value = 0 jump_offset = 0 if x in registers: test_value = registers[x] else: test_value = int(x) if test_value != 0: if y in registers: jump_offset = registers[y] else: jump_offset = int(y) instruction_counter += jump_offset-1 # at the end of cycle, instruction_counter # will be incremented from `jump_offset-1` # to `jump_offset` run = {'set': set_op, 'sub': sub_op, 'mul': mul_op, 'jnz': jnz_op} while instruction_counter < program_length: op = program[instruction_counter][0] args = program[instruction_counter][1:] run[op](*args) instruction_counter +=1 print("Part 1: " + str(mul_count)) # Part 2 registers['a'] = 1 registers['b'] = 0 registers['c'] = 0 registers['d'] = 0 registers['e'] = 0 registers['f'] = 0 registers['g'] = 0 registers['h'] = 0 instruction_counter = 0 # This program outputs the number of # composite numbers between 106700 and # 123700 with a step size of 17. prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397] num_of_composites = 0 for num in range(106700, 123717, 17): print(num, end=" ") for prime in prime_numbers: if num % prime==0: num_of_composites+=1 break optimised_program = [["set", "h", str(num_of_composites)]] program_length = len(optimised_program) while instruction_counter < program_length: op = optimised_program[instruction_counter][0] args = optimised_program[instruction_counter][1:] run[op](*args) instruction_counter += 1 register_h = registers["h"] print("Part 2: " + str(register_h))