Created
October 18, 2016 21:51
-
-
Save gkucmierz/a9323348f7188a2689764fdaf37ebdac to your computer and use it in GitHub Desktop.
Calculate Levenshtein Distance using iterative method
This file contains hidden or 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 levenshteinDistance(a, b) { | |
| if (a.length === 0) return b.length; | |
| if (b.length === 0) return a.length; | |
| let matrix = []; | |
| for (let i = 0; i <= b.length; ++i) { | |
| matrix[i] = [i]; | |
| } | |
| for (let j = 0; j <= a.length; ++j) { | |
| matrix[0][j] = j; | |
| } | |
| for (let i = 1; i <= b.length; ++i) { | |
| for (let j = 1; j <= a.length; ++j) { | |
| if (b[i-1] === a[j-1]) { | |
| matrix[i][j] = matrix[i-1][j-1]; | |
| } else { | |
| matrix[i][j] = Math.min( | |
| matrix[i-1][j-1] + 1, | |
| matrix[i][j-1] + 1, | |
| matrix[i-1][j] + 1 | |
| ); | |
| } | |
| } | |
| } | |
| return matrix[b.length][a.length]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment