-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbrainfuck.py
44 lines (32 loc) · 1.05 KB
/
brainfuck.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from collections import defaultdict
def jump_stack(code):
stack = []
jumps = {}
for i, cmd in enumerate(code):
if cmd == "[":
stack.append(i)
if cmd == "]":
start = stack.pop(-1)
jumps[start] = i
jumps[i] = start
return jumps
def brainfuck_emulator(code, input):
code, input = list(code), list(input)
ptr, i, output, memory = 0, 0, [], defaultdict(int)
js = jump_stack(code)
while i < len(code):
cmd = code[i]
# Input/Output
if cmd == ",": memory[ptr] = ord(input.pop(0))
if cmd == ".": output.append(chr(memory[ptr]))
# Move pointer
if cmd == ">": ptr += 1
if cmd == "<": ptr -= 1
# Incr/Decr memory
if cmd == "+": memory[ptr] = (memory[ptr] + 1) % 256
if cmd == "-": memory[ptr] = (memory[ptr] - 1) % 256
# Loops
if cmd == "[": i = js[i] if memory[ptr] == 0 else i
if cmd == "]": i = js[i] if memory[ptr] != 0 else i
i += 1
return "".join(output)