Last active
February 15, 2018 09:29
-
-
Save 0xrgb/3b71cc150073d4e9a251ef8303db11ee to your computer and use it in GitHub Desktop.
Simple Brainfuck interpreter
This file contains 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
# Python 3 | |
# Simple brainfuck interpreter for challenge | |
import sys | |
import re | |
def clean_code(x): | |
return re.sub(r'[^\[\]\.<>+-]', '', x) | |
def find_loop(x): | |
y = dict() | |
z = [] | |
for i in range(len(x)): | |
if x[i] == '[': | |
z.append(i) | |
elif x[i] == ']': | |
rev = z.pop(-1) | |
y[i] = rev | |
y[rev] = i | |
assert(len(z) == 0) | |
return y | |
def run(code, loop): | |
mp = 0 | |
cp = 0 | |
bf_mem = dict() | |
while cp < len(code): | |
if code[cp] == '+': | |
bf_mem[mp] = bf_mem.get(mp, 0) + 1 | |
elif code[cp] == '-': | |
bf_mem[mp] = bf_mem.get(mp, 0) - 1 | |
elif code[cp] == '.': | |
print(bf_mem.get(mp, 0)) | |
elif code[cp] == '>': | |
mp += 1 | |
elif code[cp] == '<': | |
mp -= 1 | |
elif code[cp] == '[': | |
if bf_mem.get(mp, 0) == 0: | |
cp = loop[cp] | |
elif code[cp] == ']': | |
cp = loop[cp] - 1 | |
cp += 1 | |
if __name__ == '__main__': | |
bf_code = sys.stdin.read() | |
bf_code = clean_code(bf_code) | |
bf_loop = find_loop(bf_code) | |
run(bf_code, bf_loop) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment