Created
April 8, 2018 04:12
-
-
Save jaybosamiya/2c4a0b711852c62d1286b45d1f5ccab3 to your computer and use it in GitHub Desktop.
Hacky interpreter for a subset of brainfuck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
####################################################### | |
# A hacky interpreter for the ><+-[] language | |
# 2018 (c) Jay Bosamiya | |
####################################################### | |
####################################################### | |
# Update "program" and "cells" to whatever you chose | |
####################################################### | |
program = "INPUT PROGRAM HERE" # For example, try "+>+" | |
cells = [0, 0, 0, 0, 0, 0] # Starting values for the cells | |
####################################################### | |
# DO NOT MODIFY ANYTHING BELOW THIS LINE | |
####################################################### | |
pc = 0 | |
dp = 0 | |
def move_right(): | |
global pc, dp, cells | |
dp += 1 | |
while len(cells) <= dp: | |
cells += [0] | |
pc += 1 | |
def move_left(): | |
global pc, dp | |
assert dp > 0, "Moving left past the left end" | |
dp -= 1 | |
pc += 1 | |
def increment(): | |
global pc, cells | |
cells[dp] += 1 | |
cells[dp] %= 255 | |
pc += 1 | |
def decrement(): | |
global pc, cells | |
if cells[dp] == 0: | |
cells[dp] = 256 | |
cells[dp] -= 1 | |
pc += 1 | |
def open_brace(): | |
global pc | |
pc += 1 | |
if cells[dp] != 0: | |
return | |
else: | |
c = 1 | |
while c > 0: | |
if program[pc] == '[': | |
c += 1 | |
elif program[pc] == ']': | |
c -= 1 | |
pc += 1 | |
def close_brace(): | |
global pc | |
if cells[dp] == 0: | |
pc += 1 | |
return | |
else: | |
pc -= 1 | |
c = 1 | |
while c > 0: | |
if program[pc] == '[': | |
c -= 1 | |
elif program[pc] == ']': | |
c += 1 | |
pc -= 1 | |
pc += 1 | |
while pc < len(program): | |
if program[pc] in '><+-[]': | |
# print program, pc, dp | |
# print (' ' * pc) + '^' | |
{ | |
'>': move_right, | |
'<': move_left, | |
'+': increment, | |
'-': decrement, | |
'[': open_brace, | |
']': close_brace | |
}[program[pc]]() | |
else: | |
pc += 1 | |
while len(cells) > 0 and cells[-1] == 0: | |
cells = cells[:-1] | |
cells += [0, 0, 0] | |
print "Result:", ' '.join(str(x) + ',' for x in cells), '...' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment