forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevenshteinDistance.js
More file actions
Latest commit
51 lines (45 loc) · 1.24 KB
/
Copy pathLevenshteinDistance.js
File metadata and controls
51 lines (45 loc) · 1.24 KB
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
/**
* @function calculateLevenshteinDp
* @description A Dynamic Programming based solution for calculation of the Levenshtein Distance.
* @param {String} x - Word to be converted.
* @param {String} y - Desired result after operations.
* @return {Integer} The Levenshtein distance between x and y.
* @see [Levenshtein_distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
*/
functionminimum(a,b,c){
if(a<b&&a<c){
returna
}elseif(b<a&&b<c){
returnb
}else{
returnc
}
}
functioncostOfSubstitution(x,y){
returnx===y ? 0 : 1
}
// Levenshtein distance between x and y
functioncalculateLevenshteinDp(x,y){
constdp=newArray(x.length+1)
for(leti=0;i<x.length+1;i++){
dp[i]=newArray(y.length+1)
}
for(leti=0;i<x.length+1;i++){
for(letj=0;j<y.length+1;j++){
if(i===0){
dp[i][j]=j
}elseif(j===0){
dp[i][j]=i
}else{
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
)
}
}
}
returndp[x.length][y.length]
}
export{calculateLevenshteinDp}