如何获得789之前所有可能的数字组合


how to get all possible combinations of digits until 789?

我正在尝试编写算法,以获得所有组合,并同时递增一,从而获得这个

function generate($index){
    $xxx = '';
    $flag = 0;  
    $lengtchString = strlen($index); 
    for($y = 0; $y != $lengtchString; $y++) {
        $xxx .= "$y";
    }
    while ($flag != $lengtchString ) 
    { 
        for ($i = 0; $i<$lengtchString-1; $i++) 
        {            
            $temp = $xxx[$i];  
            $xxx[$i] = $xxx[$i+1]; 
            $xxx[$i+1] = $temp;   
            echo $xxx."<br>"; 
        } 
        $flag++; 
    }
}
generate('abc');

输出为

102
120
210
201
021
012

我不仅需要得到3数字的所有组合,还需要得到所有组合。

例如,如果我写"abc"。。。我需要像一样的输出

102
120
210
201
021
012
256
874
569
236
254
028

依此类推……直到789在数字不重复的条件下。。。我真的很震惊,无法找到合适的算法。提前感谢

检查此链接PHP算法,从单个集合生成特定大小的所有组合

    <?php
    function sampling($chars, $size, $combinations = array()) {
    $charsArray = str_split($chars);
    # if it's the first iteration, the first set 
    # of combinations is the same as the set of characters
    if (empty($combinations)) {
        $combinations = $charsArray;
    }
    # we're done if we're at size 1
    if ($size == 1) {
        return $combinations;
    }
    # initialise array to put new values in
    $new_combinations = array();
    # loop through existing combinations and character set to create strings
    foreach ($combinations as $combination) {
        foreach ($charsArray as $char) {
            $new_combinations[] = $combination . $char;
        }
    }
    # call same function again for the next iteration
    return sampling($chars, $size - 1, $new_combinations);
}
// example
$output = sampling("0123456789", 3);
print "<pre>";print_r($output);

Delphi函数从给定的字符集生成所有字符组合,不包含字符重复(如果源字符串中没有重复)。

工作原理:
让我们在某个阶段进行

charset = '1203456789'
incomplete result = '12'
i goes from 3 to 10
i = 3:  charset doesn't change; recursive call executes with '123' and StartIndex = 4
i = 4: charset changes to '1204356789'; recursive call executes with '124' and StartIndex = 4; 
       charset changes back to '1203456789'
i = 5: charset changes to '12054356789'; recursive call executes with '125' and StartIndex = 4; 
       charset changes back to '1203456789'

等等…

procedure GenString(StartIndx, MaxLen: Integer; Charset, Result: string);
procedure Swap(a,b: Integer);
var
  t: Char;
begin
  t := CharSet[a];
  CharSet[a] := CharSet[b];
  CharSet[b] := t;
end;
var
  i: Integer;
begin
  if Length(Result) = MaxLen then
    Memo1.Lines.Add(Result)  // output result
  else begin
    for i := StartIndx to Length(Charset) do begin
      Swap(i, StartIndx);  //save current char to avoid further usage
      GenString(StartIndx + 1, MaxLen, Charset, Result + Charset[StartIndx]);
      Swap(i, StartIndx); //restore order
    end;
  end;
end;
usage: //Delphi strings are 1-based!
  GenString(1, 3, '0123456789', '');

输出(720个值):

012
013
014
015
016
017
018
019
021
023
024
025
026
027
028
029
032
031
...
986
987
981
980
902
903
904
905
906
907
908
901