Skip to content

Instantly share code, notes, and snippets.

@AndyChenYH
Created August 31, 2018 15:22
Show Gist options
  • Select an option

  • Save AndyChenYH/f3ca01e9f989ef5bd836bfe2749f7093 to your computer and use it in GitHub Desktop.

Select an option

Save AndyChenYH/f3ca01e9f989ef5bd836bfe2749f7093 to your computer and use it in GitHub Desktop.
Brainfrick interpreter created by Andi_Chin - https://repl.it/@Andi_Chin/Brainfrick-interpreter
import copy
#given the position of one braket, the program has to output the position of the matching bracket
#EDIT: I did it yes finally!
def find_parens(s):
toret = {}
pstack = []
for i, c in enumerate(s):
if c == '[':
pstack.append(i)
elif c == ']':
if len(pstack) == 0:
return 'errorrr'
toret[pstack.pop()] = i
if len(pstack) > 0:
return 'unpaired brakets'
return toret
def matchBracket(code, index): # the code index is 0 - based
torit = find_parens(code) #torit is excactly the same as toret
newTorit = {}
for key, value in torit.items(): #make a new dictionary with key and value swapped
newTorit[value] = key
if code[index] == '[':
return torit[index] #burrito / toret index is 0 - based
elif code[index] == ']':
return newTorit[index]
def Brainfrick(code):
i = 0
cells = [lala * 0 for lala in range(10000)]
pointer = 0
output = ''
while i != len(code): #last character of code
if code[i] == '+':
if cells[pointer] == 255:
cells[pointer] = 0
else:
cells[pointer] += 1
elif code[i] == '-':
if cells[pointer] == 0:
cells[pointer] = 255
else:
cells[pointer] -= 1
elif code[i] == '>':
pointer += 1
elif code[i] == '<':
if pointer == 0:
raise ValueError('tape out of range at ' + str(i) + 'th char of code')
pointer -= 1
elif code[i] == '.':
print('[' + 'cell ' + str(pointer) + ']' + ':' + str(chr(cells[pointer])))
output += str(chr(cells[pointer]))
elif code[i] == '[':
if cells[pointer] == 0:
i = matchBraket(code, i) # jumps to the matching close braket
# else/otherwise pointer is not 0, loops begins!
elif code[i] == ']':
if cells[pointer] != 0:
i = matchBracket(code, i)
#elif current cell is 0, keep going to the next slice of code
i += 1
print()
print('Out:')
print(output)
#test:
Brainfrick('--[----->+<]>---.++++++++++++.+.+++++++++.+[-->+<]>+++.++[-->+++<]>.++++++++++++.+.+++++++++.-[-->+++++<]>++.[--->++<]>-.-----------.')
Brainfrick('++++++[>++++++<-]>.<++++[>++++<-]>+.+++....')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment