/
interface.go
97 lines (83 loc) · 1.92 KB
/
interface.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
package turingmachines
import (
"fmt"
"github.com/rgeoghegan/tabulate"
)
type Direction bool
const (
LEFT Direction = false
RIGHT Direction = true
)
func (d Direction) String() string {
if d == RIGHT {
return "R"
}
return "L"
}
type StateCollection interface {
NumStates() int
GetState(int) State
StartState() State
}
type State interface {
IsHalt() bool
IsLoop() bool
IsUndefined() bool
String() string
GetInt() int
}
type SymbolCollection interface {
NumSymbols() int
GetSymbol(int) Symbol
Zero() Symbol
}
type Symbol interface {
String() string
GetInt() int
}
type TuringMachine interface {
StateCollection
SymbolCollection
Transition(State, Symbol) (Symbol, Direction, State)
NameString() string
}
//----------- functions for printing ------------------
func GetTMTable(tm TuringMachine) string {
var table [][]string
for i := 0; i < tm.NumStates(); i += 1 {
newRow := []string{tm.GetState(i).String()}
for j := 0; j < tm.NumSymbols(); j += 1 {
symbol, direction, state := tm.Transition(tm.GetState(i), tm.GetSymbol(j))
if state.IsUndefined() {
newRow = append(newRow, "---")
} else {
newRow = append(newRow, fmt.Sprintf("%v%v%v", symbol, direction, state))
}
}
table = append(table, newRow)
}
header := []string{""}
for j := 0; j < tm.NumSymbols(); j += 1 {
header = append(header, tm.GetSymbol(j).String())
}
layout := &tabulate.Layout{Headers: header, Format: tabulate.SimpleFormat}
asText, _ := tabulate.Tabulate(
table, layout,
)
return asText
}
func GetStandardTMFormat(tm TuringMachine) string {
tmString := ""
for i := 0; i < tm.NumStates(); i += 1 {
for j := 0; j < tm.NumSymbols(); j += 1 {
symbol, direction, state := tm.Transition(tm.GetState(i), tm.GetSymbol(j))
if state.IsUndefined() {
tmString += "---"
} else {
tmString += fmt.Sprintf("%v%v%v", symbol, direction, state)
}
}
tmString += "_"
}
return tmString[:len(tmString)-1]
}