1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
function Minimum( Val1, Val2, Cost: Integer): Integer;
begin
Result := Cost;
if Result > Val1 then
Result := Val1;
if Result > Val2 then
Result := Val2;
end;
function FastLevensteinDistance( AText1: String; AText2: String; AMaxDistance: Integer): Integer;
var Matrix: array of Integer;
Len1, Len2, i, j, ActualCost, NextCost, LastCost: Integer;
begin
Len1 := Length( AText1);
Len2 := Length( AText2);
if Len1 = 0 then begin
Result := Len2;
Exit;
end;
if Len2 = 0 then begin
Result := Len1;
Exit;
end;
SetLength( Matrix, Len2 + 1);
try
LastCost := Len2;
for j := 1 to Len2 - 1 do
Matrix[ j] := j;
for i := 1 to Len1 do begin
LastCost := i;
ActualCost := Len2;
for j := 1 to Len2 do begin
NextCost := Minimum( Matrix[ j] + 1, LastCost + 1, Matrix[ j - 1] + IfThen( AText1[ i] = AText2[ j], 0, 1));
Matrix[ j - 1] := LastCost;
LastCost := NextCost;
ActualCost := FastMin( ActualCost, LastCost);
end;
if ActualCost > AMaxDistance then begin
Result := AMaxDistance + 1;
Exit;
end else
Matrix[ Len2] := LastCost;
end;
Result := LastCost;
finally
SetLength( Matrix, 0);
end;
end; |
Partager