Skip to content

Instantly share code, notes, and snippets.

@vv198x
Last active March 13, 2023 14:02
Show Gist options
  • Save vv198x/7f8d6ee07ce0ab35e824857a8e189ed7 to your computer and use it in GitHub Desktop.
Save vv198x/7f8d6ee07ce0ab35e824857a8e189ed7 to your computer and use it in GitHub Desktop.
Brainfuck interpreter
/* Brainfuck is an esoteric programming language created in 1993 by Urban Müller.
Except for its two I/O commands, Brainfuck is a minor variation of the formal programming language P′′
created by Corrado Böhm in 1964, which in turn is explicitly based on the Turing machine.
In fact, using six symbols equivalent to the respective Brainfuck commands +, -, <, >, [, ],
Böhm provided an explicit program for each of the basic functions that together serve to compute any computable function.
*/
package main
import ("fmt", "io/ioutil")
func main() {
code, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
tape := make([]byte, 30000)
pointer := 0
output := ""
for i := 0; i < len(code); i++ {
command := code[i]
switch command {
case '>':
pointer++
case '<':
pointer--
case '+':
tape[pointer]++
case '-':
tape[pointer]--
case '.':
output += string(tape[pointer])
case ',':
fmt.Scanf("%c", &tape[pointer])
case '[':
if tape[pointer] == 0 {
loop_depth := 1
for loop_depth > 0 {
i++
if code[i] == '[' {
loop_depth++
} else if code[i] == ']' {
loop_depth--
}
}
}
case ']':
if tape[pointer] != 0 {
loop_depth := 1
for loop_depth > 0 {
i--
if code[i] == '[' {
loop_depth--
} else if code[i] == ']' {
loop_depth++
}
}
}
}
}
fmt.Println(output)
}
@vv198x
Copy link
Author

vv198x commented Mar 13, 2023

Note that this implementation assumes that the Brainfuck code in the input.txt file is valid and doesn't contain any syntax errors. If you want to add error checking, you can modify the code to check for mismatched loop brackets, invalid characters, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment