-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdat.go
More file actions
147 lines (125 loc) · 2.37 KB
/
Copy pathdat.go
File metadata and controls
147 lines (125 loc) · 2.37 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
package aho_corasick
import (
"bufio"
"fmt"
"github.com/orbit-w/aho_corasick/lib/math"
"github.com/orbit-w/aho_corasick/lib/number_utils"
"io"
"os"
"sort"
)
/*
@Author: orbit-w
@File: dat
@2023 10月 周二 18:56
*/
type DAT struct {
len int
cap int // 底层数据的真实容量
base []int // 转移基数
check []int // dat 映射父子节点唯一关系性
}
func (ins *DAT) LoadDict(path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
buf := bufio.NewReader(file)
sks := StrKeySlice{}
for {
line, _, err := buf.ReadLine()
if err != nil {
if err != io.EOF {
return err
}
break
}
sks = append(sks, []rune(string(line)))
}
sort.Sort(sks)
trie := new(Trie)
trie.Build(sks)
ins.Build(trie)
return nil
}
func (ins *DAT) init() {
ins.cap = InitSize
ins.base = make([]int, InitSize)
ins.check = make([]int, InitSize)
ins.base[IndexRoot] = StateRoot
return
}
func (ins *DAT) Build(trie *Trie) {
ins.init()
builder := NewBuilder()
trie.BFS(func(father *Node) (stop bool) {
builder.insert(ins, father)
return
})
}
func (ins *DAT) Find(keyword []rune) bool {
var index int = IndexRoot
for _, r := range keyword {
i := ins.getState(index) + int(r)
if !ins.exist(i, index) {
return false
}
index = i
}
return ins.base[index] < 0
}
func (ins *DAT) Length() int {
return ins.len
}
func (ins *DAT) Cap() int {
return ins.cap
}
func (ins *DAT) exist(i, state int) bool {
if i >= ins.cap {
return false
}
return ins.check[i] == state
}
func (ins *DAT) getState(i int) int {
return number_utils.ABS[int](ins.base[i])
}
func (ins *DAT) Empty(s int) bool {
if s >= ins.len {
return true
}
return ins.check[s] == 0 && ins.base[s] == 0
}
func (ins *DAT) resize(in int) {
if ins.cap >= in {
if ins.len < in {
ins.len = in
}
return
}
ins.cap = math.PowerOf2(in)
ins.len = in
ins.malloc()
}
func (ins *DAT) malloc() {
newBase := make([]int, ins.cap)
copy(newBase, ins.base)
ins.base = newBase
newCheck := make([]int, ins.cap)
copy(newCheck, ins.check)
ins.check = newCheck
}
// setState 更新 base[state]
func (ins *DAT) setState(index, state int, isLeaf bool) {
if isLeaf {
ins.base[index] = -state
} else {
ins.base[index] = state
}
}
func (ins *DAT) Print() {
fmt.Println("Base: ", ins.base)
fmt.Println("Check: ", ins.check)
}