6 ms·
Here's a python script for the simple machine and a 9 instruction solution program. It won't work if the addends are zero. The 0 case can be handled by checki
by asanagi 11y ago
Here's a python script for the simple machine and a 9 instruction solution program. It won't work if the addends are zero. The 0 case can be handled by checking for 0 and jumping ahead of the increment loop.
class VM(object):
memory = []
ip = 0
while len(memory) < 1000:
memory.append(0)
memory[0] = 3
memory[1] = 4
def z(idx):
VM.memory[idx] = 0
VM.ip += 1
def i(idx):
VM.memory[idx] += 1
VM.ip += 1
def j(idx, cmp, goto):
if VM.memory[idx] == VM.memory[cmp]:
VM.ip += 1
else:
VM.ip = goto
program = (
(z, (2,)), #0 INITIALIZE USED MEMORY
(z, (3,)), #1
(z, (4,)), #2
(i, (2,)), #3 BEGIN LOOP, INCREMENT m[2]
(i, (3,)), #4 INCREMENT m[3]
(j, (3, 0, 3)), #5 LOOP UNTIL memory[3] == memory[0]
(i, (2,)), #6 SIM.
(i, (4,)), #7
(j, (4, 1, 6)) #8
)
def run():
while VM.ip < len(program):
func, args = program[VM.ip]
func(*args)
run()
print VM.memory[2]