-
Notifications
You must be signed in to change notification settings - Fork 0
/
wagner_fischer.go
75 lines (65 loc) · 1.82 KB
/
wagner_fischer.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
package levenshtein
// FullMatrixDistance calculate the distance between two strings using the Levenshtein
// Distance algorithm, with the [Wagner Fischer] algorithm.
//
// The Wagner-Fischer algorithm can be optimized by utilizing only two matrix rows,
// which is implemented by [TwoRowsDistance].
//
// [Wagner Fischer]: https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
func FullMatrixDistance(a, b string) int {
la, lb := len(a), len(b)
d := make([][]int, la+1)
for i := 0; i <= la; i++ {
d[i] = make([]int, lb+1)
}
for i := 0; i <= la; i++ {
d[i][0] = i
}
for j := 1; j <= lb; j++ {
d[0][j] = j
}
for i := 1; i <= la; i++ {
for j := 1; j <= lb; j++ {
substitutionCost := 1
if a[i-1] == b[j-1] {
substitutionCost = 0
}
d[i][j] = min(
d[i-1][j]+1, // deletion
d[i][j-1]+1, // insertion
d[i-1][j-1]+substitutionCost, // substitution
)
}
}
return d[la][lb]
}
// TwoRowsDistance calculate the distance between two strings using the Levenshtein
// Distance algorithm, with the Wagner–Fischer algorithm, with the [two matrix rows]
// optimization.
//
// This is an optimization of the [FullMatrixDistance] function.
//
// [two matrix rows]: https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_two_matrix_rows
func TwoRowsDistance(a, b string) int {
la, lb := len(a), len(b)
prev, curr := make([]int, lb+1), make([]int, lb+1)
for j := 0; j <= lb; j++ {
prev[j] = j
}
for i := 0; i < la; i++ {
curr[0] = i + 1
for j := 0; j < lb; j++ {
substitutionCost := 1
if a[i] == b[j] {
substitutionCost = 0
}
curr[j+1] = min(
prev[j+1]+1, // deletion
curr[j]+1, // insertion
prev[j]+substitutionCost, // substitution
)
}
prev, curr = curr, prev
}
return prev[lb]
}