MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / levenshteinDistance

Function levenshteinDistance

String/LevenshteinDistance.js:12–41  ·  view source on GitHub ↗
(a, b)

Source from the content-addressed store, hash-verified

10*/
11
12const 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 // Initializing first column:
19 for (let i = 0; i <= a.length; i += 1) {
20 distanceMatrix[0][i] = i
21 }
22
23 // Initializing 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 return distanceMatrix[b.length][a.length]
41}
42
43export { levenshteinDistance }

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected