Part 1
In this puzzle we are asked to implement a simple cpu with 4 registers and 4 different instructions. The instructions are a copy, increment, decrement and a conditional jump. We are then given a small program and we should return the result of this program after its run.
We implement the registers and the pointer to the current instruction (instruction pointer or "ip") as a simple dictionary. We then loop and check the instrucion pointed to by the ip. We use regex to figure out which instruction we should exectute and to parse the operands.
def execute(line, registers):
m = re.match("cpy (.+) (.+)", line)
if m:
source = m.group(1)
target = m.group(2)
return execute_cpy(registers, source, target)
m = re.match("inc (.+)", line)
if m:
target = m.group(1)
return execute_inc(registers, target)
m = re.match("dec (.+)", line)
if m:
target = m.group(1)
return execute_dec(registers, target)
m = re.match("jnz (.+) (.+)", line)
if m:
condition = m.group(1)
target = m.group(2)
return execute_jnz(registers, condition, target)
print("Invalid operation", line)
return registers
Once we hit the end of the program, we return the content of the "a" register as the result.
We could speed up the execution by not using regex everytime and caching the result. But the program was fast enough for it not to be necessary.
Part 2
In part 2, we should initialize a register with a different value before the start. Since the solution from part 1 was fast enough, nothing else was needed.
Bonus
The program we are executing computes the first fibonacci numbers and adds another constant on top of it. When initialized differently in part 2, the program just increases the length of the fibonacci sequence.
No comments:
Post a Comment