Skip to content

Instantly share code, notes, and snippets.

@relsqui
Created November 23, 2013 13:21
Show Gist options
  • Save relsqui/7614544 to your computer and use it in GitHub Desktop.
Save relsqui/7614544 to your computer and use it in GitHub Desktop.
One-instruction computer.
2 5 0
0 2
2 1
2 2
1 3 0
1 1
0 2
2 1
2 2
[finnre@rita subleq]$ ./subleq.py copy
[1, 3, 0]
(1, 1)
[1, 0, 0]
(0, 2)
[1, 0, -1]
(2, 1)
[1, 1, -1]
(2, 2)
[1, 1, 0]
#!/usr/bin/python
import fileinput
def subleq(a, b, c):
global memory
memory[b] -= memory[a]
if memory[b] <= 0:
return c
return None
def run(program):
global memory
pointer = 0
while pointer >= 0 and pointer < len(program):
instruction = program[pointer]
print memory
print instruction
if len(instruction) < 3:
instruction = instruction + (pointer + 1,)
a, b, c = instruction
newpointer = subleq(a, b, c)
if newpointer is None:
pointer += 1
else:
pointer = newpointer
memory = []
program = []
for line in fileinput.input():
# The first line of the file is starting memory.
# The rest are sets of operands. Blank lines are ignored.
if line == "\n":
continue
if fileinput.isfirstline():
memory = map(int, line.split())
else:
program.append(tuple(map(int, line.split())))
run(program)
print memory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment