Create an Unknown Number of Loops

后端 未结 1 1754
名媛妹妹
名媛妹妹 2021-01-06 03:10

this is my simple code to generate all possible combinations of a set for example

1,2,3:

  • Display: 123 132 213 231 312 321

i want to c

相关标签:
1条回答
  • 2021-01-06 03:43

    Here is some code that produces the output you desire. You'd need to work it around a bit for your needs, but the concept expressed in this recursive solution is the important thing:

    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.
    

    Output:

    123
    132
    213
    231
    312
    321
    

    If you change the definition of TElements, for example to '1'..'4' then you will see the 24 possible permutations.

    0 讨论(0)
提交回复
热议问题