Last active
March 11, 2024 05:57
-
-
Save mohnish/936f0fa3d783373784147b5e3dd48985 to your computer and use it in GitHub Desktop.
Calculating Edit Distance between 2 strings using Levenshtein's algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function editDistance(word1, word2) { | |
return levenshteinDistance(word1, word2, 0, 0); | |
} | |
function levenshteinDistance(word1, word2, i, j) { | |
if (i == word1.length) { | |
return word2.length - j; | |
} else if (j == word2.length) { | |
return word1.length - i; | |
} else { | |
let min = 0; | |
if (word1[i] == word2[j]) { | |
min = levenshteinDistance(word1, word2, i + 1, j + 1); | |
} else { | |
min = 1 + Math.min( | |
levenshteinDistance(word1, word2, i, j + 1), | |
levenshteinDistance(word1, word2, i + 1, j), | |
levenshteinDistance(word1, word2, i + 1, j + 1) | |
); | |
} | |
return min; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment