forked from mkideal/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fuzzy.go
71 lines (59 loc) · 1.26 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
package cli
func match(s, t string) (float32, bool) {
return matchWithMinDifferRate(s, t, 0.3)
}
func matchWithMinDifferRate(s, t string, minDifferRate float32) (float32, bool) {
dist := editDistance([]byte(s), []byte(t))
differRate := float32(dist) / float32(max(len(s), len(t))+4)
return differRate, differRate <= minDifferRate
}
func editDistance(s, t []byte) float32 {
var (
m = len(s)
n = len(t)
d = make([][]float32, m+1)
)
for i := 0; i < m+1; i++ {
d[i] = make([]float32, n+1)
d[i][0] = float32(i)
}
for j := 0; j < n+1; j++ {
d[0][j] = float32(j)
}
for j := 1; j < n+1; j++ {
for i := 1; i < m+1; i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
d[i][j] = min(d[i-1][j]+1, min(d[i][j-1]+1, d[i-1][j-1]+1))
}
}
}
return d[m][n]
}
func min(x, y float32) float32 {
if x < y {
return x
}
return y
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
type editDistanceRank struct {
s string
d float32
}
type editDistanceRankSlice []editDistanceRank
func (dists editDistanceRankSlice) Len() int {
return len(dists)
}
func (dists editDistanceRankSlice) Less(i, j int) bool {
return dists[i].d < dists[j].d
}
func (dists editDistanceRankSlice) Swap(i, j int) {
dists[i], dists[j] = dists[j], dists[i]
}