Skip to content

Instantly share code, notes, and snippets.

@exallium
Created May 15, 2013 18:02
Show Gist options
  • Save exallium/5585969 to your computer and use it in GitHub Desktop.
Save exallium/5585969 to your computer and use it in GitHub Desktop.
Iterative Levenshtein Distance algorithm adapted from http://en.wikipedia.org/wiki/Levenshtein_distance
// Iterative with two matrix rows
function lev(left, right) {
// Degenerative Cases
if (left == right) return 0;
if (left.length == 0) return right.length;
if (right.length == 0) return left.length;
var vectorLength = right.length + 1;
var workVector0 = new Array();
var workVector1 = new Array();
for (var i = 0; i < vectorLength; i++) {
workVector0[i] = i;
}
for (var i = 0; i < left.length; i++) {
workVector1[0] = i + 1;
for (var j = 0; j < right.length; j++) {
var cost = (left[i] == right[j]) ? 0 : 1;
workVector1[j + 1] = Math.min(workVector1[j] + 1, workVector0[j + 1] + 1, workVector0[j] + cost);
}
for (var j = 0; j < vectorLength; j++) {
workVector0[j] = workVector1[j];
}
}
return workVector1[right.length];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment