Source: site.view [edit]
Function name: levenshteinDistance
Arguments: s,t
Description: Informally, the Levenshtein distance between two words is the minimum number of single-character edits (insertion, deletion, substitution) required to change one word into the other.
Page type: webl
Render function:  
Module: global

Page source:

var Minimum = fun(a, b)
   if a < b then
      return a
   else
      return b
   end
end;

var Minimum3 = fun(a, b, c)
   Minimum(a, Minimum(b, c))
end;


var levDist = fun(s, t)

    // degenerate cases
    if (s == t) then return 0 end;
    if (Size(s) == 0) then return Size(t) end;
    if (Size(t) == 0) then return Size(s) end;
 
    // create two work vectors of integer distances
    var v0 = [. .];
    var v1 = [. .];
 
    // initialize v0 (the previous row of distances)
    // this row is A[0][i]: edit distance for an empty s
    // the distance is just the number of characters to delete from t
    var i = 0;
    while (i < Size(t)+1) do
        v0[i] := i;
        i = i + 1
    end;
 
    i = 0;
    while i < Size(s) do
        // calculate v1 (current row distances) from the previous row v0
 
        // first element of v1 is A[i+1][0]
        //   edit distance is delete (i+1) chars from s to match empty t
        v1[0] := i + 1;
 
        // use formula to fill in the rest of the row
        var j = 0;
        while (j < Size(t)) do
            var cost;
            if (s[i] == t[j]) then
               cost = 0
            else 
               cost = 1
            end;
            v1[j + 1] := Minimum3(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);
            j = j + 1
        end;
 
        j = 0;
        while (j < Size(t)+1) do
           v0[j] := v1[j];
           j = j + 1
        end;
                      
        i = i + 1
    end;
 
    return v1[Size(t)];
end;
            
levDist(s, t);