Skip to content

Instantly share code, notes, and snippets.

@yatt
Created April 15, 2011 03:49
Show Gist options
  • Save yatt/921109 to your computer and use it in GitHub Desktop.
Save yatt/921109 to your computer and use it in GitHub Desktop.
brainf*ck interpreter
from sys import stdin, stdout
# state
class Int(object):
def __init__(self, v=0): self.val = v
def set(self, v): self.val = v; return self.val
def inc(self): self.val += 1; return self.val
def dec(self): self.val -= 1; return self.val
mem = [Int() for i in range(255)]
stk = []
ptr = Int()
idx = Int(-1)
# procedure
proc = {
'+': lambda: mem[ptr.val].inc(),
'-': lambda: mem[ptr.val].dec(),
'>': lambda: ptr.inc(),
'<': lambda: ptr.dec(),
',': lambda: mem[ptr.val].set(ord(stdin.read(1))),
'.': lambda: stdout.write(chr(mem[ptr.val].val)),
'[': lambda: stk.append(idx.val),
']': lambda: mem[ptr.val].val != 0 and idx.set(stk[-1]) or stk.pop(),
}
# interpret
bfprog = stdin.read()
while len(bfprog) != idx.inc():
proc.get(bfprog[idx.val], lambda:1)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment