Skip to content

Instantly share code, notes, and snippets.

@milesrout
Created December 20, 2016 22:54
Show Gist options
  • Save milesrout/88cf41f8004526126c951b7e1193f804 to your computer and use it in GitHub Desktop.
Save milesrout/88cf41f8004526126c951b7e1193f804 to your computer and use it in GitHub Desktop.
import collections
import random
def randprog(length=12):
return ''.join(random.choice('><+-[]') for i in range(length))
def execute(prog, tape):
i = 0
j = 0
l = len(prog)
total = 0
ctrl = []
jumps = {}
tape[0]
for k, x in enumerate(prog):
if x == '[':
ctrl.append(k)
if x == ']':
try:
n = ctrl.pop()
except:
return -1
jumps[k] = n
jumps[n] = k
if ctrl != []:
return -1
while j != l:
c = prog[j]
if c == '>':
i += 1
elif c == '<':
i -= 1
elif c == '+':
if tape[i] == 255:
tape[i] = 0
else:
tape[i] += 1
elif c == '-':
if tape[i] == 0:
tape[i] = 255
else:
tape[i] -= 1
elif c == '[':
if tape[i] == 0:
j = jumps[j]
elif c == ']':
if tape[i] != 0:
j = jumps[j]
elif c == 'h':
break
j += 1
total += 1
if total >= 100000:
return total
return total
def stringify(tape):
return '[' + ''.join('{:3x}'.format(tape[i]) for i in range(min(tape), max(tape))) + ']'
print('\t')
for i in range(25):
prog = randprog()
tape = collections.defaultdict(int)
total = execute(prog, tape)
if total != -1:
print(total, '\t', prog, stringify(tape))
#print(execute('+[><]', [0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment