PHP列出数组元素的所有组合

时间:2014-12-06 15:51:34

标签: php arrays process combinations

我有一个数组:

$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);
}
}

谢谢。

2 个答案:

答案 0 :(得分:1)

此代码将组合识别为二进制数,使用的事实是formula表示可能来自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 :(得分:0)

我编辑并使用了您的功能,如下所示。再次感谢Lajos。

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/>';
    }
}
相关问题