-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuzzy.go
119 lines (106 loc) · 2.61 KB
/
fuzzy.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
package dawg
type FuzzySearchResult struct {
Word string
Error float32
}
func FuzzySearch(d *DAWG, word string) []FuzzySearchResult {
foundWords := make(map[string]float32, 0)
runes := []rune(word)
lenRunes := len(runes)
// FIXME: 誤差に関するパラメータ。決め打ちになっているが、変更可能であるべき。
k := float32(2.0) // 最大許容誤差
ie := float32(1.0) // insertion error
de := float32(1.0) // deletion error
se := float32(2.0) // substitution error
te := float32(2.0) // transposition error
type Stack struct {
Error float32
Node map[rune]int32
Pos int
Substr string
}
stack := []Stack{{
Node: d.DFA[0],
}}
for len(stack) > 0 {
curr := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// deletion error
if curr.Error+de <= k {
for r, idxTo := range curr.Node {
if r != -1 {
stack = append(stack, Stack{
Error: curr.Error + de,
Node: d.DFA[idxTo],
Pos: curr.Pos,
Substr: curr.Substr + string(r),
})
}
}
}
// found
if curr.Pos == lenRunes {
if _, ok := curr.Node[-1]; ok {
if merr, ok := foundWords[curr.Substr]; !ok || merr < curr.Error {
foundWords[curr.Substr] = curr.Error
}
}
continue
}
currRune := runes[curr.Pos]
// hit
if idxTo, ok := curr.Node[currRune]; ok && idxTo >= 0 {
stack = append(stack, Stack{
Error: curr.Error,
Node: d.DFA[idxTo],
Pos: curr.Pos + 1,
Substr: curr.Substr + string(currRune),
})
}
// insertion error
if curr.Error+ie <= k {
stack = append(stack, Stack{
Error: curr.Error + ie,
Node: curr.Node,
Pos: curr.Pos + 1,
Substr: curr.Substr,
})
}
// substitution error
if curr.Error+se <= k {
for r, idxTo := range curr.Node {
if r != -1 && r != currRune {
stack = append(stack, Stack{
Error: curr.Error + se,
Node: d.DFA[idxTo],
Pos: curr.Pos + 1,
Substr: curr.Substr + string(r),
})
}
}
}
// transposition error
if (curr.Error+te <= k) && (curr.Pos < lenRunes-1) {
runeNext := runes[curr.Pos+1]
if idxNext, ok := curr.Node[runeNext]; ok && idxNext >= 0 {
if idxTo, ok := d.DFA[idxNext][currRune]; ok && idxTo >= 0 {
stack = append(stack, Stack{
Error: curr.Error + te,
Node: d.DFA[idxTo],
Pos: curr.Pos + 1,
Substr: curr.Substr + string(currRune),
})
}
}
}
}
// 結果を配列に変換
results := make([]FuzzySearchResult, 0)
for word, merr := range foundWords {
results = append(results, FuzzySearchResult{
Word: word,
Error: merr,
})
}
return results
}