diff options
| author | Richard Qin <richard.qin.001@gmail.com> | 2026-09-15 08:16:43 +0800 |
|---|---|---|
| committer | Richard Qin <richard.qin.001@gmail.com> | 2026-09-15 08:16:43 +0800 |
| commit | 4022e5c95210631e4aceb08eaf9d9071aa5aefc4 (patch) | |
| tree | a5922559836e45fb3459a3d070367912e1035b1a /tests/sysy_lvX/071_brainfk.sy | |
| download | rcc-master.tar.gz rcc-master.tar.xz | |
Diffstat (limited to 'tests/sysy_lvX/071_brainfk.sy')
| -rw-r--r-- | tests/sysy_lvX/071_brainfk.sy | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/tests/sysy_lvX/071_brainfk.sy b/tests/sysy_lvX/071_brainfk.sy new file mode 100644 index 0000000..d1ee0c1 --- /dev/null +++ b/tests/sysy_lvX/071_brainfk.sy @@ -0,0 +1,73 @@ +/* +a brainfuck interpreter +reference: https://gist.github.com/maxcountryman/1699708 +*/ + +// tape, input buffer, and read/write pointer +const int TAPE_LEN = 65536, BUFFER_LEN = 32768; +int tape[TAPE_LEN], program[BUFFER_LEN], ptr = 0; + +// read the input program +void read_program() { + int i = 0, len = getint(); + while (i < len) { + program[i] = getch(); + i = i + 1; + } + program[i] = 0; +} + +// interpret the input program +void interpret(int input[]) { + int cur_char, loop, i = 0; + while (input[i]) { + cur_char = input[i]; + if (cur_char == 62) { + // '>' + ptr = ptr + 1; + } + else if (cur_char == 60) { + // '<' + ptr = ptr - 1; + } + else if (cur_char == 43) { + // '+' + tape[ptr] = tape[ptr] + 1; + } + else if (cur_char == 45) { + // '-' + tape[ptr] = tape[ptr] - 1; + } + else if (cur_char == 46) { + // '.' + putch(tape[ptr]); + } + else if (cur_char == 44) { + // ',' + tape[ptr] = getch(); + } + else if (cur_char == 93 && tape[ptr]) { + // ']' + loop = 1; + while (loop > 0) { + i = i - 1; + cur_char = input[i]; + if (cur_char == 91) { + // '[' + loop = loop - 1; + } + else if (cur_char == 93) { + // ']' + loop = loop + 1; + } + } + } + i = i + 1; + } +} + +int main() { + read_program(); + interpret(program); + return 0; +} |
