Skip to content

Instantly share code, notes, and snippets.

@BlakeWilliams
Created November 14, 2011 09:55
Show Gist options
  • Save BlakeWilliams/1363641 to your computer and use it in GitHub Desktop.
Save BlakeWilliams/1363641 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in Go
package main
import (
"strings"
"fmt"
)
var cells [30000]int
var commands []string
var ptr = 0
var pos = 0
func main() {
commands := strings.Split("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.", "")
for pos != len(commands) {
execute(commands)
pos += 1
}
}
func execute(commands []string) {
switch commands[pos] {
case ">": ptr += 1
case "<": ptr -= 1
case "+": cells[ptr] += 1
case "-": cells[ptr] -= 1
case "[": if cells[ptr] == 0 { nxt() }
case "]": if cells[ptr] != 0 { lst() }
case ".": fmt.Printf("%c", cells[ptr])
}
}
func nxt() {
var brackets = 1
for brackets != 0 {
pos += 1
switch commands[pos] {
case "]": brackets--
case "[": brackets++
}
}
}
func lst() {
var brackets = 1
for brackets != 0 {
pos -= 1
switch commands[pos] {
case "]": brackets++
case "[": brackets--
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment