Skip to content

Commit d1e958b

Browse files
committed
fix: wrong Levenshtein distance when minimum options tie
1 parent 5c39e87 commit d1e958b

2 files changed

Lines changed: 13 additions & 11 deletions

File tree

‎Dynamic-Programming/LevenshteinDistance.js‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,6 @@
77
* @see [Levenshtein_distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
88
*/
99

10-
function minimum(a, b, c) {
11-
if (a < b && a < c) {
12-
return a
13-
} else if (b < a && b < c) {
14-
return b
15-
} else {
16-
return c
17-
}
18-
}
19-
2010
function costOfSubstitution(x, y) {
2111
return x === y ? 0 : 1
2212
}
@@ -35,7 +25,7 @@ function calculateLevenshteinDp(x, y) {
3525
} else if (j === 0) {
3626
dp[i][j] = i
3727
} else {
38-
dp[i][j] = minimum(
28+
dp[i][j] = Math.min(
3929
dp[i - 1][j - 1] +
4030
costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)),
4131
dp[i - 1][j] + 1,

‎Dynamic-Programming/tests/LevenshteinDistance.test.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,15 @@ test('Should return the distance for strings with different length', () => {
1717
const to = 'saturday'
1818
expect(calculateLevenshteinDp(from, to)).toBe(3)
1919
})
20+
21+
test('Should return the right distance when two of the three options tie', () => {
22+
expect(calculateLevenshteinDp('aabaab', 'aaba')).toBe(2)
23+
expect(calculateLevenshteinDp('baab', 'cac')).toBe(3)
24+
})
25+
26+
test('Should return the distance for equal and empty strings', () => {
27+
expect(calculateLevenshteinDp('abc', 'abc')).toBe(0)
28+
expect(calculateLevenshteinDp('', 'abc')).toBe(3)
29+
expect(calculateLevenshteinDp('abc', '')).toBe(3)
30+
expect(calculateLevenshteinDp('', '')).toBe(0)
31+
})

0 commit comments

Comments
 (0)