Part 1
In this puzzle, we have a list of instructions for a custom processor. These instruction are setting variables, subtracting, multiplication and conditional jumps. We are asked to implement a program executing the provided processor and count the number of multiplication instructions.
We have a dictionary for all the registers from a to h and a register for the current line number. In each step, we look at the current line and then parse and execute the instruction:
instruction = instructions[registers["ip"]]
opcode, operands = instruction
exec_instruction(opcode, operands, registers)
registers["ip"] += 1
if registers["ip"] < 0 or registers["ip"] >= len(instructions):
break
The execution itself is straight forward, we just need to remember the conditional jump needs an offset of -1, because we later increase it by 1. For quicker parsing, we parse the instuctions before the execution instead of in the execution loop.
The counting the number of multiplications was done in the main loop by checking the current instruction:
...
if opcode == "mul":
num_muls += 1
...
Part 2
In part 2, we need to run the same program again after initializing the a register to 1. We should return the h register after the program hits its end.
When simply setting a to 1, it became clear the program takes too long to finish. So a different approach was needed. We checked the instructions and tried to figure out the program.
The program checks all numbers in range certain range whether they are prime numbers. It then counts the number of non-primes and return that in the h register.
After realising that, we emulated the functionality with the constants hardcoded.
No comments:
Post a Comment