我试图编写算法以获得所有组合并同时增加一个并获得此
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
...
我的想法实际上是被吹,无法得到适当的算法。提前谢谢
答案 0 :(得分:0)
点击此链接PHP algorithm to generate all combinations of a specific size from a single set
<?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);
答案 1 :(得分:0)
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