Created
December 11, 2021 13:24
-
-
Save eloonstra/6d8568ba97337f0f6e9bddfef907bed6 to your computer and use it in GitHub Desktop.
A 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
package brainfuck | |
func Interpreter(code string, input string) string { | |
memory := make([]int, 30000) | |
var ( | |
output string | |
pointer, inputPointer int | |
loopStack []int | |
) | |
for i := 0; i < len(code); i++ { | |
switch code[i] { | |
case '>': | |
pointer++ | |
case '<': | |
pointer-- | |
case '+': | |
memory[pointer]++ | |
case '-': | |
memory[pointer]-- | |
case '.': | |
output += string(rune(memory[pointer])) | |
case ',': | |
if inputPointer < len(input) { | |
memory[pointer] = int(input[inputPointer]) | |
inputPointer++ | |
} | |
case '[': | |
if memory[pointer] == 0 { | |
i = loopStack[len(loopStack)-1] | |
} else { | |
loopStack = append(loopStack, i) | |
} | |
case ']': | |
if memory[pointer] != 0 { | |
i = loopStack[len(loopStack)-1] | |
} else { | |
loopStack = loopStack[:len(loopStack)-1] | |
} | |
} | |
} | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment