Skip to content

Commit 8eb370a

Browse files
authored
Merge pull request #60 from luiz-mai/levenshtein-distance
Levenshtein distance
2 parents ca23fb2 + 497ae1a commit 8eb370a

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

strings/levenshteinDistance.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
This algorithm calculates the distance between two strings.
3+
Parameters: two strings to compare and weights of insertion, substitution and deletion.
4+
Output: distance between both strings
5+
*/
6+
7+
package main
8+
9+
import (
10+
"fmt"
11+
)
12+
13+
func levenshteinDistance(str1, str2 string, icost, scost, dcost int) int {
14+
row1 := make([]int, len(str2)+1)
15+
row2 := make([]int, len(str2)+1)
16+
var tmp []int
17+
18+
for i := 1; i <= len(str2); i++ {
19+
row1[i] = i * icost
20+
}
21+
22+
for i := 1; i <= len(str1); i++ {
23+
row2[0] = i * dcost
24+
25+
for j := 1; j <= len(str2); j++ {
26+
if str1[i-1] == str2[j-1] {
27+
row2[j] = row1[j-1]
28+
} else {
29+
ins := row2[j-1] + icost
30+
del := row1[j] + dcost
31+
sub := row1[j-1] + scost
32+
33+
if ins < del && ins < sub {
34+
row2[j] = ins
35+
} else if del < sub {
36+
row2[j] = del
37+
} else {
38+
row2[j] = sub
39+
}
40+
}
41+
}
42+
43+
tmp = row1
44+
row1 = row2
45+
row2 = tmp
46+
}
47+
48+
return row1[len(row1)-1]
49+
}
50+
51+
func min(str1, str2 int) int {
52+
if str1 < str2 {
53+
return str1
54+
}
55+
return str2
56+
}
57+
58+
func main() {
59+
str1 := "stingy"
60+
str2 := "ring"
61+
62+
// Using weight 1 for insertion, substitution and deletion
63+
strDistance1 := levenshteinDistance(str1, str2, 1, 1, 1)
64+
fmt.Printf("Distance between \"%s\" and \"%s\" is: %d.\n", str1, str2, strDistance1)
65+
// Output: Distance between "stingy" and "ring" is: 3.
66+
67+
// Using weight 1 for insertion/substitution and weight 3 for deletion
68+
strDistance2 := levenshteinDistance(str1, str2, 1, 1, 3)
69+
fmt.Printf("Distance between \"%s\" and \"%s\" is: %d.\n", str1, str2, strDistance2)
70+
// Output: Distance between "stingy" and "ring" is: 7.
71+
72+
return
73+
}

0 commit comments

Comments
 (0)