5

这是我生成一组所有可能组合的简单代码,例如

1,2,3:

  • 显示:123 132 213 231 312 321

我想创建可变数量的 for 循环,让用户确定给定字符串的长度...

有没有人有想法...

提前致谢。

type
  TNumber = '0'..'9';

procedure TForm1.Button1Click(Sender: TObject);
var
  Numbers: array[0..3] of TNumber;
  a, b, c, d: Integer;
  s: string;
begin
  Numbers[0] := '1';
  Numbers[1] := '8';
  Numbers[2] := '7';
  Numbers[3] := '2';
  for a := low(Numbers) to High(Numbers) do
    for b := low(Numbers) to High(Numbers) do
      for c := low(Numbers) to High(Numbers) do
        for d := low(Numbers) to High(Numbers) do
        begin
          s := Numbers[a] + Numbers[b] + Numbers[c]  + Numbers[d];
          if
            (Occurrences('1', s) > 1 ) or
            (Occurrences('8', s) > 1 ) or
            (Occurrences('7', s) > 1 ) or
            (Occurrences('2', s) > 1 )
          then
            Continue
          else
            Memo1.Lines.Add(s);
  end;
end;

function TForm1.Occurrences(const Substring, Text: string): Integer;
var
  Offset: Integer;
begin
  Result := 0;
  Offset := PosEx(Substring, Text, 1);
  while Offset <> 0 do
  begin
    Inc(Result);
    Offset := PosEx(Substring, Text, offset + length(Substring));
  end;
end;

结尾。

4

1 回答 1

9

这是一些产生您想要的输出的代码。您需要根据自己的需要对其进行一些处理,但是此递归解决方案中表达的概念很重要:

program Permuatations;

{$APPTYPE CONSOLE}

type
  TElements = '1'..'3';

procedure EnumerateCombinations(const Stem: string; Len: Integer);
var
  i: Integer;
  el: TElements;
  Used: set of TElements;
begin
  if Len=0 then
    exit;
  Used := [];
  for i := 1 to Length(Stem) do
    Include(Used, Stem[i]);
  for el := low(el) to high(el) do
  begin
    if el in Used then
      continue;
    if Len=1 then
      Writeln(Stem+el)
    else
      EnumerateCombinations(Stem+el, Len-1)
  end;
end;

procedure Main;
begin
  EnumerateCombinations('', 1+ord(high(TElements))-ord(low(TElements)));
end;

begin
  Main;
  Readln;
end.

输出:

123
132
213
231
312
321

例如,如果您将 的定义更改为TElements'1'..'4'您将看到 24 种可能的排列。

于 2012-08-26T17:30:23.943 回答