1package bf
2
3import (
4 "strings"
5)
6
7const maxlen = 30000
8
9func Execute(code string) string {
10 var (
11 memory = make([]byte, maxlen) // memory tape
12 pointer = 0 // initial memory pointer
13 buf strings.Builder
14 )
15
16 // Loop through each character in the code
17 for i := 0; i < len(code); i++ {
18 switch code[i] {
19 case '>':
20 // Increment memory pointer
21 pointer++
22 if pointer >= maxlen {
23 pointer = 0
24 }
25 case '<':
26 // Decrement memory pointer
27 pointer--
28 if pointer < 0 {
29 pointer = maxlen - 1
30 }
31 case '+':
32 // Increment the byte at the memory pointer
33 memory[pointer]++
34 case '-':
35 // Decrement the byte at the memory pointer
36 memory[pointer]--
37 case '.':
38 // Output the byte at the memory pointer
39 buf.WriteByte(memory[pointer])
40 case ',':
41 // Input a byte and store it in the memory
42 panic("unsupported")
43 // fmt.Scan(&memory[pointer])
44 case '[':
45 // Jump forward past the matching ']' if the byte at the memory pointer is zero
46 if memory[pointer] == 0 {
47 braceCount := 1
48 for braceCount > 0 {
49 i++
50 if code[i] == '[' {
51 braceCount++
52 } else if code[i] == ']' {
53 braceCount--
54 }
55 }
56 }
57 case ']':
58 // Jump backward to the matching '[' if the byte at the memory pointer is nonzero
59 if memory[pointer] != 0 {
60 braceCount := 1
61 for braceCount > 0 {
62 i--
63 if code[i] == ']' {
64 braceCount++
65 } else if code[i] == '[' {
66 braceCount--
67 }
68 }
69 i-- // Move back one more to compensate for the upcoming increment in the loop
70 }
71 }
72 }
73 return buf.String()
74}
bf.gno
1.57 Kb ยท 74 lines