-
Notifications
You must be signed in to change notification settings - Fork 3
/
levenshtein.go
135 lines (129 loc) · 2.47 KB
/
levenshtein.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package levenshtein
var peq [0x10000]uint64
func m64(a string, b string) int {
pv := ^uint64(0)
mv := uint64(0)
sc := 0
for _, c := range a {
peq[c] |= uint64(1) << sc
sc++
}
ls := uint64(1) << (sc - 1)
for _, c := range b {
eq := peq[c]
xv := eq | mv
eq |= ((eq & pv) + pv) ^ pv
mv |= ^(eq | pv)
pv &= eq
if (mv & ls) != 0 {
sc++
}
if (pv & ls) != 0 {
sc--
}
mv = (mv << 1) | 1
pv = (pv << 1) | ^(xv | mv)
mv &= xv
}
for _, c := range a {
peq[c] = 0
}
return sc
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func mx(a string, b string) int {
s1 := []rune(a)
s2 := []rune(b)
n := len(s1)
m := len(s2)
hsize := 1 + ((n - 1) / 64)
vsize := 1 + ((m - 1) / 64)
phc := make([]uint64, hsize)
mhc := make([]uint64, hsize)
for i := 0; i < hsize; i++ {
phc[i] = ^uint64(0)
mhc[i] = 0
}
j := 0
for ; j < vsize-1; j++ {
mv := uint64(0)
pv := ^uint64(0)
start := j * 64
vlen := min(64, m) + start
for k := start; k < vlen; k++ {
peq[s2[k]] |= uint64(1) << (k & 63)
}
for i := 0; i < n; i++ {
eq := peq[s1[i]]
pb := (phc[i/64] >> (i & 63)) & 1
mb := (mhc[i/64] >> (i & 63)) & 1
xv := eq | mv
xh := ((((eq | mb) & pv) + pv) ^ pv) | eq | mb
ph := mv | ^(xh | pv)
mh := pv & xh
if ((ph >> 63) ^ pb) != 0 {
phc[i/64] ^= uint64(1) << (i & 63)
}
if ((mh >> 63) ^ mb) != 0 {
mhc[i/64] ^= uint64(1) << (i & 63)
}
ph = (ph << 1) | pb
mh = (mh << 1) | mb
pv = mh | ^(xv | ph)
mv = ph & xv
}
for k := start; k < vlen; k++ {
peq[s2[k]] = 0
}
}
mv := uint64(0)
pv := ^uint64(0)
start := j * 64
vlen := min(64, m-start) + start
for k := start; k < vlen; k++ {
peq[s2[k]] |= uint64(1) << (k & 63)
}
sc := uint64(m)
for i := 0; i < n; i++ {
eq := peq[s1[i]]
pb := (phc[i/64] >> (i & 63)) & 1
mb := (mhc[i/64] >> (i & 63)) & 1
xv := eq | mv
xh := ((((eq | mb) & pv) + pv) ^ pv) | eq | mb
ph := mv | ^(xh | pv)
mh := pv & xh
sc += (ph >> ((m - 1) & 63)) & 1
sc -= (mh >> ((m - 1) & 63)) & 1
if ((ph >> 63) ^ pb) != 0 {
phc[i/64] ^= uint64(1) << (i & 63)
}
if ((mh >> 63) ^ mb) != 0 {
mhc[i/64] ^= uint64(1) << (i & 63)
}
ph = (ph << 1) | pb
mh = (mh << 1) | mb
pv = mh | ^(xv | ph)
mv = ph & xv
}
for k := start; k < vlen; k++ {
peq[s2[k]] = 0
}
return int(sc)
}
func Distance(a, b string) int {
if len(a) < len(b) {
a, b = b, a
}
if len(b) == 0 {
return len(a)
}
if len(a) <= 64 {
return m64(a, b)
}
return mx(a, b)
}