Skip to content

Instantly share code, notes, and snippets.

@yangsu
Created August 21, 2016 18:54
Show Gist options
  • Save yangsu/7374cbbeec318751d7404eb04a6716b6 to your computer and use it in GitHub Desktop.
Save yangsu/7374cbbeec318751d7404eb04a6716b6 to your computer and use it in GitHub Desktop.
Brain Fuck Intepreter
def match(code, start, reverse=False):
count = 0
begin, end = "[", "]"
if reverse:
begin, end = end, begin
search = code[:start][::-1] if reverse else code[start:]
for i, c in enumerate(search):
if c == begin:
count += 1
elif c == end:
if count == 0:
return start - i - 1 if reverse else start + i
count -= 1
def brain_luck(code, input):
memory = {}
p = 0 # memory pointer
i = 0 # code pointer
j = 0 # input pointer
output = ""
while i < len(code):
c = code[i]
if c == ">":
p += 1
elif c == "<":
p -= 1
elif c == "+":
memory[p] = (memory.get(p, 0) + 1) % 256
elif c == "-":
memory[p] = (memory.get(p, 0) - 1 + 256) % 256
elif c == ".":
output += chr(memory.get(p, 0))
elif c == ",":
memory[p] = ord(input[j])
j += 1
elif c == "[":
if memory.get(p, 0) == 0:
i = match(code, i)
continue
elif c == "]":
if memory.get(p, 0) != 0:
i = match(code, i, reverse=True) + 1
continue
i += 1
return output
s = ',>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]'
input = chr(10)
print brain_luck(s, input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment