Last active
September 22, 2016 12:51
-
-
Save melbourne2991/a3d469b9078279ab713e0ba6559d8ac5 to your computer and use it in GitHub Desktop.
Levenshtein (edit) Distance in JS
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 getDistance(strA, strB) { | |
const matrix = []; | |
const arrA = strA.split(''); | |
const arrB = strB.split(''); | |
// fill matrix with a row for each character and | |
// for each row add a single column with incrementing (0 to length) | |
for(let a = 0; a < arrA.length + 1; a++) { | |
matrix[a] = [a] | |
} | |
// fill first row with column for each character incrementing (0 to length) | |
for(let b = 0; b < arrB.length + 1; b++) { | |
matrix[0][b] = b | |
} | |
// Iterate through each unit in the matrix starting at the second row / second column | |
for(let a = 1; a < arrA.length + 1; a++) { | |
for(let b = 1; b < arrB.length + 1; b++) { | |
// calculate minimum of left unit, left diaganol unit and above unit | |
let min = Math.min( | |
matrix[a - 1][b - 1], | |
Math.min( | |
matrix[a - 1][b], | |
matrix[a][b - 1] | |
) | |
) | |
// if the two characters match, there is no cost, | |
// otherwise one operation has cost of 1 | |
matrix[a][b] = min + (arrA[a - 1] === arrB[b - 1] ? 0 : 1) | |
} | |
} | |
return matrix[arrA.length][arrB.length]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment