Created
January 4, 2012 21:57
-
-
Save IgorInger/1562394 to your computer and use it in GitHub Desktop.
Levenshtein distance (jQuery plugin)
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($) { | |
$.fn.levenshteinDistance = function(u, v) { | |
var m = u.length; | |
var n = v.length; | |
var D = []; | |
for(var i = 0; i <= m; i++) { | |
D.push([]); | |
for(var j = 0; j <= n; j++) { | |
D[i][j] = 0; | |
} | |
} | |
for(var i = 1; i <= m; i++) { | |
for(var j = 1; j <= n; j++) { | |
if (j == 0) { | |
D[i][j] = i; | |
} else if (i == 0) { | |
D[i][j] = j; | |
} else { | |
D[i][j] = [D[i-1][j-1] + (u[i-1] != v[j-1]), D[i][j-1] + 1, D[i-1][j] + 1].sort()[0]; | |
} | |
} | |
} | |
return D[m][n]; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works great in Chrome, but always returns 0 in IE8 as
u[i-1]
andv[j-1]
evaluates to undefined. Instead use str.charAt( index ) and it will work.i.e.
D[i][j] = [D[i-1][j-1] + (u.charAt(i-1) != v.charAt(j-1)), D[i][j-1] + 1, D[i-1][j] + 1].sort()[0];