Created
November 14, 2011 09:55
-
-
Save BlakeWilliams/1363641 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in Go
This file contains 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 ( | |
"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