Search code examples
algorithmdelphitstringlist

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,',9

How should I go about doing this?


Solution

  • 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;