Skip to content

Commit d792636

Browse files
authored
Added Levenshtein Distance Algorithm (TheAlgorithms#263)
1 parent cfdf6fa commit d792636

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* A Dynamic Programming based solution for calculation of the Levenshtein Distance
3+
* https://en.wikipedia.org/wiki/Levenshtein_distance
4+
*/
5+
6+
function minimum (a, b, c) {
7+
if (a < b && a < c) {
8+
return a
9+
} else if (b < a && b < c) {
10+
return b
11+
} else {
12+
return c
13+
}
14+
}
15+
16+
function costOfSubstitution (x, y) {
17+
return x === y ? 0 : 1
18+
}
19+
20+
function calculate (x, y) {
21+
const dp = new Array(x.length + 1)
22+
for (let i = 0; i < x.length + 1; i++) {
23+
dp[i] = new Array(y.length + 1)
24+
}
25+
26+
for (let i = 0; i < x.length + 1; i++) {
27+
for (let j = 0; j < y.length + 1; j++) {
28+
if (i === 0) {
29+
dp[i][j] = j
30+
} else if (j === 0) {
31+
dp[i][j] = i
32+
} else {
33+
dp[i][j] = minimum(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1, dp[i][j - 1] + 1)
34+
}
35+
}
36+
}
37+
38+
return dp[x.length][y.length]
39+
}
40+
41+
function main () {
42+
const x = '' // enter your string here
43+
const y = '' // enter your string here
44+
45+
console.log('Levenshtein distance between ' + x + ' and ' + y + ' is: ')
46+
console.log(calculate(x, y))
47+
}
48+
49+
main()

0 commit comments

Comments
 (0)