【问题标题】:How to synchronize equal lines in two stringlists如何同步两个字符串列表中的相等行
【发布时间】:2011-09-29 09:42:26
【问题描述】:

我有两个要同步的字符串列表,以便相同的行获得相同的索引,而不同的行将保留在它们最初所在的列表中,而另一个字符串列表应该为该索引获得一个“填充”。考虑这个例子:

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

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

该过程应将列表更改为此

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

或者,如果列表已排序,则到此

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

我该怎么做呢?

【问题讨论】:

  • 请澄清“如果列表已排序”是什么意思。您的示例具有相同的输入数据,并且两个列表都是有序的。
  • 对不起。如果 (aSL1.Sorted 和 aSL2.Sorted) 程序应根据字母顺序填充列表 1 或 2,但如果列表未排序,则应填充列表 2,并填充列表 1。这不是一个重要的要求。
  • 澄清更多:在问题的两个示例中,列表都是同步的,但只有在第二个示例中,“列表的并集”是排序的。
  • '2' 和 '11' 你想要什么顺序。简单的字符串比较给出 '11'
  • 字符串排序很好。我只是为这个例子做了数字。在实际应用中我会用它来处理“真实”的字符串。

标签: algorithm delphi tstringlist


【解决方案1】:

在列表单调递增的情况下试试这个。

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;

【讨论】:

  • 谢谢。我想我们想出了几乎相同的解决方案:-)
  • 一个或多个输入文件的“平衡线”处理的漂亮而简单的实现(回到我的 Cobol 时代......)
【解决方案2】:

我实际上设法制作了一种适合我需要的方法:

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;

它需要对列表进行排序,但不要让 sorted 属性为真(因为这样我们就不能插入它)

示例运行:

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

同步:

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

【讨论】:

    【解决方案3】:

    我希望某种this(Levenshtein 距离)算法可以帮助到你。

    【讨论】:

    • 不,那是完全不同的东西(但不是我投反对票:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 2023-03-14
    相关资源
    最近更新 更多