|
| 1 | +/* The Levenshtein distance (a.k.a edit distance) is a |
| 2 | +measure of similarity between two strings. It is |
| 3 | +defined as the minimum number of changes required to |
| 4 | +convert string a into string b (this is done by |
| 5 | +inserting, deleting or replacing a character in |
| 6 | +string a). |
| 7 | +The smaller the Levenshtein distance, |
| 8 | +the more similar the strings are. This is a very |
| 9 | +common problem in the application of Dynamic Programming. |
| 10 | +*/ |
| 11 | + |
| 12 | +const levenshteinDistance = (a, b) => { |
| 13 | + // Declaring array 'D' with rows = len(a) + 1 and columns = len(b) + 1: |
| 14 | + const distanceMatrix = Array(b.length + 1) |
| 15 | + .fill(null) |
| 16 | + .map(() => Array(a.length + 1).fill(null)) |
| 17 | + |
| 18 | + // Initialising first column: |
| 19 | + for (let i = 0; i <= a.length; i += 1) { |
| 20 | + distanceMatrix[0][i] = i |
| 21 | + } |
| 22 | + |
| 23 | + // Initialising first row: |
| 24 | + for (let j = 0; j <= b.length; j += 1) { |
| 25 | + distanceMatrix[j][0] = j |
| 26 | + } |
| 27 | + |
| 28 | + for (let j = 1; j <= b.length; j += 1) { |
| 29 | + for (let i = 1; i <= a.length; i += 1) { |
| 30 | + const indicator = a[i - 1] === b[j - 1] ? 0 : 1 |
| 31 | + // choosing the minimum of all three, vis-a-vis: |
| 32 | + distanceMatrix[j][i] = Math.min( |
| 33 | + distanceMatrix[j][i - 1] + 1, // deletion |
| 34 | + distanceMatrix[j - 1][i] + 1, // insertion |
| 35 | + distanceMatrix[j - 1][i - 1] + indicator // substitution |
| 36 | + ) |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + console.log( |
| 41 | + 'Levenshtein Distance between ' + |
| 42 | + a + |
| 43 | + ' and ' + |
| 44 | + b + |
| 45 | + ' is = ' + |
| 46 | + distanceMatrix[b.length][a.length] |
| 47 | + ) |
| 48 | + return distanceMatrix[b.length][a.length] |
| 49 | +} |
| 50 | + |
| 51 | +export { levenshteinDistance } |
0 commit comments