Skip to content

Instantly share code, notes, and snippets.

@alphazero
Last active March 16, 2017 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alphazero/a0b2b50e60b897595da32b9b3fa6603c to your computer and use it in GitHub Desktop.
Save alphazero/a0b2b50e60b897595da32b9b3fa6603c to your computer and use it in GitHub Desktop.
BF in go
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) < 1 {
fmt.Fprintf(os.Stderr, "usage: bf <program>")
os.Exit(1)
}
res := brainfuck(os.Args[1])
fmt.Println(res)
}
const MaxMemory = 256
func brainfuck(program string) string {
var out []byte
var inst = []byte(program)
var data = make([]byte, MaxMemory)
var dx = 0
for ix := 0; ix < len(inst); ix++ {
d := 1
switch {
case inst[ix] == '[' && data[dx] == 0:
for d > 0 {
ix++
switch inst[ix] {
case '[':
d++
case ']':
d--
}
}
case inst[ix] == ']' && data[dx] != 0:
for d > 0 {
ix--
switch inst[ix] {
case '[':
d--
case ']':
d++
}
}
case inst[ix] == '+':
data[dx]++
case inst[ix] == '-':
data[dx]--
case inst[ix] == '>':
dx++
case inst[ix] == '<':
if dx > 0 {
dx--
}
case inst[ix] == '.':
out = append(out, data[dx])
case inst[ix] == ',':
fmt.Scanf("%c", &data[dx])
default:
}
}
return string(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment