Skip to content

Commit

Permalink
strings: fix levenshtein_distance function correctness after #20435 (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
hholst80 committed Jan 10, 2024
1 parent 61cd2ee commit 0910401
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
17 changes: 12 additions & 5 deletions vlib/strings/similarity.v
@@ -1,8 +1,15 @@
module strings

@[inline]
fn imin(x u16, y u16) u16 {
return if x < y { x } else { y }
fn min(a u16, b u16, c u16) u16 {
mut m := a
if b < m {
m = b
}
if c < m {
m = c
}
return m
}

// levenshtein_distance uses the Levenshtein Distance algorithm to calculate
Expand All @@ -21,13 +28,13 @@ pub fn levenshtein_distance(a string, b string) int {

mut row := []u16{len: a.len + 1, init: u16(index)}

for i := 1; i < b.len; i++ {
for i := 1; i < b.len + 1; i++ {
mut prev := u16(i)
for j := 1; j < a.len; j++ {
for j := 1; j < a.len + 1; j++ {
mut current := row[j - 1] // match
if b[i - 1] != a[j - 1] {
// insertion, substitution, deletion
current = imin(imin(row[j - 1] + 1, prev + 1), row[j] + 1)
current = min(row[j - 1] + 1, prev + 1, row[j] + 1)
}
row[j - 1] = prev
prev = current
Expand Down
1 change: 1 addition & 0 deletions vlib/strings/similarity_test.v
Expand Up @@ -10,4 +10,5 @@ fn test_levenshtein_distance() {
assert strings.levenshtein_distance('hugs', 'shrugs') == 2
assert strings.levenshtein_distance('broom', 'shroom') == 2
assert strings.levenshtein_distance('flomax', 'volmax') == 3
assert strings.levenshtein_distance('ab', 'cd') == 2
}

0 comments on commit 0910401

Please sign in to comment.