-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
102 lines (87 loc) · 2.32 KB
/
parser.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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func readFile(filename string) (map[string][]string, error) {
// Buka file
file, err := os.Open(filename)
if err != nil {
return nil, fmt.Errorf("Gagal membuka file: %v", err)
}
defer file.Close()
// Membaca file baris per baris
scanner := bufio.NewScanner(file)
productions := make(map[string][]string)
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
continue
}
// Pisahkan simbol non-terminal dan produksi dengan delimiter "->"
parts := strings.Split(line, "->")
if len(parts) != 2 {
return nil, fmt.Errorf("Format produksi tidak valid: %s", line)
}
// Trim spasi dari simbol non-terminal dan produksi
symbol := strings.TrimSpace(parts[0])
productionsStr := strings.TrimSpace(parts[1])
// Pisahkan produksi dengan delimiter "|"
productionsArr := strings.Split(productionsStr, "|")
for i := 0; i < len(productionsArr); i++ {
productionsArr[i] = strings.TrimSpace(productionsArr[i])
}
// Tambahkan aturan produksi ke dalam map
productions[symbol] = productionsArr
}
// Cek error pembacaan file
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("Gagal membaca file: %v", err)
}
return productions, nil
}
func isAccepted(input string) bool {
filename := "d:/tubes/tba/production.txt"
productions, _:= readFile(filename)
var parse func(string, string) string
parse = func(str, symbol string) string {
if _, ok := productions[symbol]; !ok {
if len(str) > 0 && str[0] == symbol[0] {
return str[1:]
}
return ""
}
for _, production := range productions[symbol] {
remainingStr := str
valid := true
for _, part := range production {
remainingStr = parse(remainingStr, string(part))
if remainingStr == "" {
valid = false
break
}
}
if valid {
return remainingStr
}
}
return ""
}
result := parse(input, "S")
return result == ""
}
func main() {
inputString := ""
for inputString != "404"{
fmt.Println("masukkan string:")
fmt.Scan(&inputString)
if isAccepted(inputString) && inputString != "404"{
fmt.Printf("String %s diterima\n", inputString)
} else {
fmt.Printf("String %s tidak diterima\n", inputString)
}
fmt.Println(" ")
}
}