-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.go
67 lines (60 loc) · 1.08 KB
/
brainfuck.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package brainfuck
import (
"bufio"
"errors"
"io"
)
func Brainfuck(file io.Reader) (string, error) {
scanner := bufio.NewScanner(file)
var res string
for scanner.Scan() {
res += scanner.Text()
}
return interpretBrainfuck(res)
}
func interpretBrainfuck(code string) (string, error) {
memory := make([]byte, len(code)*len(code))
var pointer int
var output string
for i := 0; i < len(code); i++ {
switch code[i] {
case '>':
pointer++
case '<':
pointer--
case '+':
memory[pointer]++
case '-':
memory[pointer]--
case '.':
output += string(memory[pointer])
case '[':
if memory[pointer] == 0 {
loopCount := 1
for loopCount > 0 {
i++
if code[i] == '[' {
loopCount++
} else if code[i] == ']' {
loopCount--
}
}
}
case ']':
if memory[pointer] != 0 {
loopCount := 1
for loopCount > 0 {
i--
if code[i] == ']' {
loopCount++
} else if code[i] == '[' {
loopCount--
}
}
}
default:
return "", errors.New("compiler error: unknown char")
}
}
return output, nil
}