-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
69 lines (63 loc) · 985 Bytes
/
main.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
68
69
package main
import (
"fmt"
"os"
)
var memory = []byte{0}
var program []byte
var mp = 0
func runOp(i int, c byte) int {
switch c {
case '>':
mp++
memory = append(memory, 0)
case '<':
if mp == 0 {
panic("out of bounds")
}
mp--
case '+':
memory[mp]++
case '-':
memory[mp]--
case '.':
fmt.Printf("%c", memory[mp])
case ',':
var s string
fmt.Scan(&s)
memory[mp] = byte(s[0])
case '[':
k := i + 1
for ; program[k] != ']'; k++ {
}
for memory[mp] != 0 {
for j := i + 1; j < k; j++ {
j += runOp(j, program[j])
}
}
return k - i
case ']':
panic("unmatched ]")
case '\n', '\r', '\t', ' ':
case '#':
j := i + 1
for j < len(program) && program[j] != '\n' {
j++
}
return j - i
default:
panic("unknown char: " + string(c))
}
return 0
}
func main() {
p, err := os.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
program = p
for i := 0; i < len(program); i++ {
i += runOp(i, program[i])
}
fmt.Println()
}