对于我糟糕的英语,我很高兴.我正在尝试从str:TStringList(Xn,Yn)生成符号组合,其中X是新单词中char的位置,Y是位置的变量.
例如,假设我的StringList有
str[0]: '013456789'
str[1]: 'abcdef'
str[2]: '5421'
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我将表达216个单词(长度(str [0])*length(str [1])*length(str [2]))结果如下:
str[0][1]+ str[1][1]+ str[2][1] -> 0a5
str[0][1]+ str[1][1]+ str[2][2] -> 0a4
str[0][1]+ str[1][1]+ str[2][3] -> 0a2
str[0][1]+ str[1][1]+ str[2][4] -> 0a1
str[0][1]+ str[1][2]+ str[2][1] -> 0b5
str[0][1]+ str[1][2]+ str[2][2] -> 0b4
str[0][1]+ str[1][2]+ str[2][3] -> 0b2
str[0][1]+ str[1][2]+ str[2][4] -> 0b1
str[0][1]+ str[1][3]+ str[2][1] -> 0c5
str[0][1]+ str[1][3]+ str[2][2] -> 0c4
str[0][1]+ str[1][3]+ str[2][3] -> 0c2
str[0][1]+ str[1][3]+ str[2][4] -> 0c1
Run Code Online (Sandbox Code Playgroud)
直到等等
str[0][10]+ str[1][6]+ str[2][3] -> 9f2
str[0][10]+ str[1][6]+ str[2][4] -> 9f1
Run Code Online (Sandbox Code Playgroud)
现在我已经注意到如何使"FOR"循环为每个可能的单词制作cicles.
最好的问候马丁
这可以通过递归来完成。
procedure Recurse(startIx,stopIx: Integer; prefix: String; const aList: TStringList);
var
ch : Char;
begin
if (startIx > stopIx) then begin
WriteLn(prefix);
end
else
begin
for ch in aList[startIx] do begin
Recurse( startIx+1,stopIx,prefix + ch,aList);
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
Recurse(0,str.Count-1,'',str);
Run Code Online (Sandbox Code Playgroud)
递归乍一看似乎很神奇,但它是解决此类组合数学的一种非常有效的方法。
这个问题的解决方案是Cartesian product
.
如果您有较旧的 Delphi 版本,请像这样迭代该字符:
procedure Recurse(startIx,stopIx: Integer; prefix: String; const aList: TStringList);
var
i : Integer;
begin
if (startIx > stopIx) then begin
WriteLn(prefix);
end
else
begin
for i := 1 to Length(aList[startIx]) do begin
Recurse( startIx+1,stopIx,prefix + aList[startIx][i],aList);
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
251 次 |
最近记录: |