Created
August 21, 2016 18:54
-
-
Save yangsu/7374cbbeec318751d7404eb04a6716b6 to your computer and use it in GitHub Desktop.
Brain Fuck Intepreter
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
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