Skip to content

Instantly share code, notes, and snippets.

@jiornojiovanni
Last active November 16, 2021 12:43
Show Gist options
  • Save jiornojiovanni/c4a6658b8a2b909a469cf9136f7b1377 to your computer and use it in GitHub Desktop.
Save jiornojiovanni/c4a6658b8a2b909a469cf9136f7b1377 to your computer and use it in GitHub Desktop.
My take on a Go brainfuck interpreter (Input must be only valid brainfuck characters, so no spaces or new lines)
package main
import (
"bufio"
"fmt"
"log"
"os"
"strings"
)
func main() {
var state [30000]byte
position := 0
ip := 0
input, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
log.Fatal(err)
}
input = strings.TrimSuffix(input, "\n")
for ip != len(input) {
switch input[ip] {
case '>':
position++
ip++
case '<':
position--
ip++
case '+':
state[position]++
ip++
case '-':
state[position]--
ip++
case '.':
fmt.Printf("%c", state[position])
ip++
case ',':
input, err := bufio.NewReader(os.Stdin).ReadByte()
if err != nil {
log.Fatal(err)
}
state[position] = input
ip++
case '[':
if state[position] == 0 {
skip := 0
i := ip + 1
found := false
//We search the bracket pair, ignoring all the inner pairs.
//This works because a valid brainfuck program must have matching pairs.
for !found {
switch input[i] {
case '[':
skip++
case ']':
if skip != 0 {
skip--
} else {
ip = i + 1
found = true
}
}
i++
}
} else {
ip++
}
case ']':
if state[position] != 0 {
skip := 0
i := ip - 1
found := false
//Same as the previous case, but we search backwards.
for !found {
switch input[i] {
case ']':
skip++
case '[':
if skip != 0 {
skip--
} else {
ip = i + 1
found = true
}
}
i--
}
} else {
ip++
}
}
}
fmt.Print("\r")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment