как получить все возможные комбинации цифр до 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 при условии, что цифры не повторятся …
мой разум на самом деле взорван, не могу получить правильный алгоритм для этого. заранее спасибо

2

Решение

Проверьте эту ссылку Алгоритм 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);
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
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector