PHP список всех комбинаций элементов массива

У меня есть массив:

$arr=array("A","B","C");

Я хочу сделать все это как:

array("A")
array("B")
array("C")
array("A","B")
array("A","C")
array("B","C")
array("A","B","C")

Я хочу обработать все эти комбинации, но я не хочу генерировать все комбинации, сохранять их в массиве и применять к ним функции. Потому что для этого требуется много памяти с большими комбинациями. У меня есть 40 предметов для этого процесса (у меня много времени, но мне не хватает памяти).

Я хочу иметь такую ​​функцию:

function ProcessArrayCombinations($array){
foreach($array as $v){
//generate and process next combination of array
print_r($nextcombination);
}
}

Спасибо.

-1

Решение

Этот код распознает комбинации как двоичные числа, используя тот факт, что есть формула который утверждает, что сумма всех возможных комбинаций из n элементов равна 2 ^ n. Зная, что его двоичный логарифм является целым числом, мы можем определить модель, в которой каждое возможное двоичное число, построенное из n цифр, является набором комбинаций. Код не проверен, если есть опечатки, пожалуйста, дайте мне знать в комментариях.

function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}

$elementCount = count($status);
$trues = 0;

while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
//for ($i = 0; $i < count($status); $i++) {
//    if ($status[$i}) {
//        print
//    } else {
//        don't print
//    }
//}
}
}
1

Другие решения

Я отредактировал и использовал вашу функцию, как показано ниже. Еще раз спасибо, Лайос.

function ProcessArrayCombinations($array) {
$status = array();
foreach ($array as $element) {
$status[] = false;
}

$elementCount = count($status);
$trues = 0;

while ($trues < $elementCount) {
$index = 0;
$stop = false;
while ((!$stop) && ($index < count($status)) && ($status[$index])) {
$status[$index] = false;
$trues--;
$index++;
}
$status[$index] = true;
$trues++;
//Found a new combination
//We should print elements from $array located at indexes fulfilling
//the criteria that the element having the same index in $status is true:
for ($i = 0; $i < count($status); $i++) {
if ($status[$i]) {
echo $array[$i];
}
}
echo '<br/>';
}
}
0

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