public
Last active — forked from 140bytes/LICENSE.txt

Levenshtein Distance

  • Download Gist
LICENSE.txt
1 2 3 4 5 6 7 8 9 10 11 12 13
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
 
Copyright (C) 2011 Mathieu 'p01' Henri <http://www.p01.org/releases/>
 
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.
README.md
Markdown

Levenshtein Distance

Compute the levenshtein distance between two strings

annotated.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
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
}
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11
{
"name": "levenshteinDistance",
 
"description": "Compute the levenshtein distance between two strings.",
 
"keywords": [
"levenshtein",
"strings",
"distance"
]
}
test.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<!DOCTYPE html>
<title>Levenshtein Distance</title>
<div>Expected value: <b>3,1,0,1,3</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var L=function(a,b,c,d,e,f,g){for(d=[e=0];a[e++];)for(c=[f=0];b[++f];)g=d[f]=e-1?Math.min(d[--f],c[f]-(a[e]==b[f]),c[++f]=d[f])+1:f;return g};
 
document.getElementById('ret').innerHTML = [
L('sitting','kitten')
,L('kitten','mitten')
,L('kitten','kitten')
,L('mitten','kitten')
,L('kitten','sitting')
];
</script>

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...

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

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.

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.