Skip to content

Instantly share code, notes, and snippets.

@dmitmel
Last active August 20, 2016 08:10
Show Gist options
  • Save dmitmel/7353923be3762f55c5e6 to your computer and use it in GitHub Desktop.
Save dmitmel/7353923be3762f55c5e6 to your computer and use it in GitHub Desktop.
Interpreter for language "brainfuck".
# Python 2.7 interpreter of esoteric programming language named "Brainfu**". You can reed more here:
# https://en.wikipedia.org/wiki/Brainfuck
# To run this interpreter, just type something like this:
#
# Interpreter.run('++++++++++[.-]')
#
# (This program will print numbers from 10 to 1)
MEMORY_SIZE = 30000
SIZE_OF_CELL = 256
class Interpreter(object):
@staticmethod
def run(code):
selected_cell = 0
# Stack trace for loops
stack_trace = []
memory = [0 for _ in xrange(MEMORY_SIZE)]
i = 0
while i < len(code):
char = code[i]
if char == '>':
if selected_cell == MEMORY_SIZE - 1:
selected_cell = 0
selected_cell += 1
elif char == '<':
if selected_cell == 0:
selected_cell = MEMORY_SIZE - 1
selected_cell -= 1
elif char == '+':
if memory[selected_cell] == SIZE_OF_CELL - 1:
memory[selected_cell] = 0
memory[selected_cell] += 1
elif char == '-':
if memory[selected_cell] == 0:
memory[selected_cell] = SIZE_OF_CELL - 1
memory[selected_cell] -= 1
elif char == '.':
print memory[selected_cell]
elif char == ',':
memory[selected_cell] = int(raw_input())
elif char == '[':
opened = 0
closed = 0
start = 0
prev_opened = 0
end = len(code)
for j in range(i, len(code)):
if code[j] == '[':
opened += 1
if code[j] == ']':
closed += 1
if opened != 0 and prev_opened == 0:
start = j
if opened != 0 and closed != 0 and opened == closed:
end = j
break
prev_opened = opened
stack_trace.append({'start': start, 'end': end})
if memory[selected_cell] == 0:
i = end
elif char == ']':
if not memory[selected_cell] == 0:
for item in stack_trace:
if item['end'] == i and memory[selected_cell] != 0:
i = item['start']
break
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment