-
Notifications
You must be signed in to change notification settings - Fork 1
/
tape.go
134 lines (121 loc) · 2.3 KB
/
tape.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Implementation a tape for Turing Machine (busybeaver)
package main
import (
"errors"
"fmt"
)
// Constants in CAPITALS
const LENGHT = 25
// -Tape is 'finit' tape of byte (char) whith the head position
type tape struct {
t []byte
h int // head position
}
// New tape
func newt(tp *tape, lenght int) {
tp.t = make([]byte, lenght)
for i := range tp.t {
tp.t[i] = '0'
}
tp.h = lenght / 2
}
// Print tape
func printt(tp tape) {
//fmt.Println("Tape lenght: ", len(tp.t))
if len(tp.t) != 0 {
//fmt.Println("Head position: ", tp.h)
fmt.Print("[")
for i := 0; i < len(tp.t); i++ {
if tp.t[i] == 0 {
fmt.Print(" ")
} else {
fmt.Printf("%c", tp.t[i])
}
}
fmt.Println("]")
fmt.Print("[")
for i := 0; i < tp.h; i++ {
fmt.Print(".")
}
fmt.Print("^")
for i := tp.h + 1; i < len(tp.t); i++ {
fmt.Print(".")
}
fmt.Println("]")
}
}
// Print tape with the step number
func printtn(tp tape, s int) {
//fmt.Println("Tape lenght: ", len(tp.t))
if len(tp.t) != 0 {
//fmt.Println("Head position: ", tp.h)
fmt.Print(s, ":[")
for i := 0; i < len(tp.t); i++ {
if tp.t[i] == 0 {
fmt.Print(" ")
} else {
fmt.Printf("%c", tp.t[i])
}
}
fmt.Println("]")
fmt.Print(s, ":[")
for i := 0; i < tp.h; i++ {
fmt.Print(".")
}
fmt.Print("^")
for i := tp.h + 1; i < len(tp.t); i++ {
fmt.Print(".")
}
fmt.Println("]")
}
}
// Read character
func readt(tp tape) byte {
return tp.t[tp.h]
}
// Write character
func writet(tp *tape, c byte) {
tp.t[tp.h] = c
}
// Shift the head of the tape
func shiftt(tp *tape, shift byte) error {
l := len(tp.t) - 1
switch shift {
case 'L', 'l', '0': // 0 definition in <computerphile>
{
if tp.h > 0 {
tp.h--
} else {
return errors.New("ERROR: No space on the left side of the tape")
}
}
case 'R', 'r', '1': // 1 definition in <computerphile>
{
if tp.h < l {
tp.h++
} else {
return errors.New("ERROR: No space on the right side of the tape")
}
}
default:
return errors.New("ERROR: Don't move the head position")
}
return nil
}
func number1s(tp tape) int {
n := 0
for i := 0; i < len(tp.t); i++ {
if tp.t[i] == 49 {
n++
}
}
return n
}
// This helper will streamline our error checks below.
func check(e error) error {
if e != nil {
//panic(e)
fmt.Println(e)
}
return e
}