开发者

How to synchronize equal lines in two stringlists

I have two stringlists that I wish to synchronize, so that equal lines get the same index, while different lines will be kept in the list where they originally were, and the other stringlist should get a "filler" for that index. Consider this example:

SL1:  1,1,2,3,5,8 
SL2:  1,3,5,7,9

procedure SyncStringlists(aSL1,aSL2 : TStringList; aFill : string = '-');

The procedure should change the lists to this

SL1:  1,1,2,3,5,8,-,-
SL2:  1,-,-,3,5,-,7,9

or, if the lists are sorted, to this

SL1:  1,1,2,3,5,-,8,-
SL2:  1,-,-,3,5,7,开发者_如何学Python',9

How should I go about doing this?


Try this for the case where your lists are monotone increasing.

procedure SyncStringlists(SL1, SL2: TStringList; const Fill: string='-');
var
  i1, i2: Integer;
begin
  i1 := 0;
  i2 := 0;
  while (i1<SL1.Count) and (i2<SL2.Count) do begin
    if SL1[i1]<SL2[i2] then begin
      SL2.Insert(i2, Fill);
    end else if SL1[i1]>SL2[i2] then begin
      SL1.Insert(i1, Fill);
    end;
    inc(i1);
    inc(i2);
  end;
  while SL1.Count<SL2.Count do begin
    SL1.Add(Fill);
  end;
  while SL2.Count<SL1.Count do begin
    SL2.Add(Fill);
  end;
end;


I actually managed to make a method that suits my need:

procedure SyncStringlists(aSL1,aSL2 : TStringList; aFill : string = '-');
var
  I,J : integer;
begin
  I := 0;
  J := 0;

  aSL1.Sort;
  aSL2.Sort;

  while (I<aSL1.Count) and (J<aSL2.Count) do
  begin
    if aSL1[I] > aSL2[J] then
      aSL1.Insert(I,aFill)
    else if aSL1[I] < aSL2[J] then
      aSL2.Insert(J,aFill);

    inc(I);
    inc(J);
  end;

  while aSL1.Count < aSL2.Count do aSL1.Add(aFill);
  while aSL2.Count < aSL1.Count do aSL2.Add(aFill);
end;

It requires the lists to be sorted, but NOT to have the sorted property true (because then we can't insert into it)

Sample run:

SL1: 1,1,2,3,5,8,a,b,c,d,e,f
SL2: 1,3,5,7,9,e,f,g,h,i

synced:

SL1: 1,1,2,3,5,-,8,-,a,b,c,d,e,f,-,-,-
SL2: 1,-,-,3,5,7,-,9,-,-,-,-,e,f,g,h,i


I hope some kind of this (Levenshtein distance) algorithm can help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜