Previous topic

分布式系统原理

Next topic

tmux

This Page

brainfuck py

@20190820

https://en.wikipedia.org/wiki/Brainfuck http://www.muppetlabs.com/~breadbox/bf/

brainfuck解释器构成:

  • 一个线性寻址的内存区域

  • 一个指令计数器(pc, or data pointer)

指令集:

Character Meaning
> increment the data pointer (to point to the next cell to the right).
< decrement the data pointer (to point to the next cell to the left).
+ increment (increase by one) the byte at the data pointer.
- decrement (decrease by one) the byte at the data pointer.
. output the byte at the data pointer.
, accept one byte of input, storing its value in the byte at the data pointer.
[ if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command.
] if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command.

实现

class Brainfuck:
    def __init__(self):
        self.tape = [0] * 100000
        self.ptr = 0

    def inc_ptr(self):
        self.ptr += 1

    def dec_ptr(self):
        self.ptr -= 1

    def inc(self):
        self.tape[self.ptr] += 1

    def dec(self):
        self.tape[self.ptr] -= 1

    def output(self):
        print(chr(self.tape[self.ptr]), end="")

    def input(self):
        r = input()
        self.tape[self.ptr] = ord(r[0])

    def interp(self, bs):
        n = len(bs)
        i = 0
        while i < n:
            c = bs[i]
            if c == '>':
                self.inc_ptr()
            elif c == '<':
                self.dec_ptr()
            elif c == '+':
                self.inc()
            elif c == '-':
                self.dec()
            elif c == '.':
                self.output()
            elif c == ',':
                self.input()
            elif c == '[':
                if self.tape[self.ptr] == 0:
                    while bs[i] != ']':
                        i += 1
            elif c == ']':
                if self.tape[self.ptr] != 0:
                    while bs[i] != '[':
                        i -= 1
            i += 1

测试

> bf = Brainfuck()
> p0 = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
> bf.interp(p0)
Hello World!
> p1 = ",[.,]"
> bf.interp(p1)
a
ab
bc
c