credit: ShinuToki @ codewars
We want to create a simple interpreter of assembler which will support the following instructions:
mov x y- copies
y(either a constant value or the content of a register) into register
inc x- increases the content of register
dec x- decreases the content of register
jnz x y- jumps to an instruction
ysteps away (positive means forward, negative means backward), but only if
x(a constant or a register) is not zero
Register names are alphabetical (letters only). Constants are always integers (positive or negative).
jnz instruction moves relative to itself. For example, an offset of
-1 would continue at the previous instruction, while an offset of
2 would skip over the next instruction.
The function will take an input list with the sequence of the program instructions and will return a dictionary with the contents of the registers.
jnz on a register will always be followed by a
mov on the register first, so you don’t need to worry about uninitialized registers.
simple_assembler(['mov a 5','inc a','dec a','dec a','jnz a -1','inc a']) ''' visualized: mov a 5 inc a dec a dec a jnz a -1 inc a ''''
The above code will:
- set register
- increase its value by
- decrease its value by
- then decrease its value until it is zero (
jnz a -1jumps to the previous instruction if
ais not zero)
- and then increase its value by
1, leaving register
So, the function should return
I have an answer already for this, but my code was too long for system. I’m trying to make it more efficient. Thank you