Last active
December 5, 2015 20:16
-
-
Save takatoh/9684df8161e19eee5043 to your computer and use it in GitHub Desktop.
levenshtein distance implementation in Node.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
#!/usr/bin/env node | |
function levenshtein_distance(a, b) { | |
var m = []; | |
var i, j, x; | |
for (i = 0; i <= a.length; i++) { | |
m[i] = []; | |
} | |
for (i = 0; i <= a.length; i++) { | |
m[i][0] = i; | |
} | |
for (j = 0; j <= b.length; j++) { | |
m[0][j] = j; | |
} | |
for (i = 1; i <= a.length; i++) { | |
for (j = 1; j <= b.length; j++) { | |
if (a[i-1] == b[j-1]) { | |
x = 0; | |
} else { | |
x = 1; | |
} | |
m[i][j] = Math.min(m[i-1][j] + 1, m[i][j-1] + 1, m[i-1][j-1] + x); | |
} | |
} | |
return m[a.length][b.length]; | |
} | |
var s1 = process.argv[2]; | |
var s2 = process.argv[3]; | |
console.log(levenshtein_distance(s1, s2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment