Last active
March 16, 2017 11:48
-
-
Save alphazero/a0b2b50e60b897595da32b9b3fa6603c to your computer and use it in GitHub Desktop.
BF in go
This file contains hidden or 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 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