Instantly share code, notes, and snippets.

Levenshtein Distance

# Levenshtein Distance

Compute the levenshtein distance between two strings

 function( a, b, // the 2 strings to compare // now the placeholder arguments: c, d, // two row of the distance matrix e, f, // counters to loop through a and b g // the last computed distance ){ for(d=[e=0];a[e];e++) // loop through a and reset the 1st distance for(c=[f=0];b[++f];) // loop through b and reset the 1st col of the next row g= d[f]= e? // not the first row ? 1+Math.min( // then compute the cost of each change d[--f], c[f]-(a[e-1]==b[f]), c[++f]=d[f] // and copy the previous row of the distance matrix ) : // otherwise f; // init the very first row of the distance matrix return g }
 function(a,b,c,d,e,f,g){for(d=[e=0];a[e];e++)for(c=[f=0];b[++f];)g=d[f]=e?Math.min(d[--f],c[f]-(a[e-1]==b[f]),c[++f]=d[f])+1:f;return g}
 DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2011 Mathieu 'p01' Henri Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed. DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. You just DO WHAT THE FUCK YOU WANT TO.
 { "name": "levenshteinDistance", "description": "Compute the levenshtein distance between two strings.", "keywords": [ "levenshtein", "strings", "distance" ] }
 Levenshtein Distance
Expected value: 3,1,0,1,3
Actual value:

### jed commented Aug 7, 2011

 how about `Math.min(d[--f],c[f]-(a[e-1]==b[f]),c[++f]=d[f])` instead of `Math.min(d[f-1],c[f-1]-(a[e-1]==b[f-1]),c[f]=d[f])` ? EDIT: come to think of it, i think you can save some more by reordering the arguments...
Owner

### p01 commented Aug 7, 2011

 Nice catch → 135 with a minor adjustment of the outer loop Got the same feeling about shuffling the arguments or bumping the inner loop.

### jed commented Aug 7, 2011

 actually, something's wrong and the values have changed, alas. i think the endgame for this one will be merging the outer and the inner loops into one loop, like folks did with base64.
Owner

### p01 commented Aug 7, 2011

 Damn browser cache. Back to 136. I'll have a look at merging the loops, and the arrays `c` and `d`