如何获得集合中元素的所有可能组合? (电源组)

How can I get all possible combinations of element in set? (power set)

我有一个数字数组:

$numbers = array(1,2,3);

订单没有任何意义。如果给出的数字是 1、2 和 3,那么我希望收到这样的结果:

1
2
3
1 2
1 3
2 3
1 2 3

我怎样才能做到这一点?

部分解决:

PHP: How to get all possible combinations of 1D array?

然后添加了我自己的函数来清理它:

        function clean_depth_picker(&$result) {
                $results = array();
                foreach($result as $value) {
                        if ( substr_count($value, " ") == 0 ) {
                                $results[] = $value;
                        } else {
                                $arr = explode(" ", $value);
                                sort($arr);
                                $key = implode(" ", $arr);
                                if ( !in_array($key, $results) )
                                        $results[] = $key;
                        }
                }
                $result = $results;
        }

您可以使用以下递归函数:

function powerSet($arr) {
    if (!$arr) return array([]);
    $firstElement = array_shift($arr);
    $recursionCombination = powerSet($arr);
    $currentResult = [];
    foreach($recursionCombination as $comb) {
        $currentResult[] = array_merge($comb, [$firstElement]);
    }
    return array_merge($currentResult, $recursionCombination );
}

现在 print_r(powerSet([1,2,3])); 将为您提供所有这些选项作为数组。

编辑为添加空数组选项作为 powerSet

可能是我在旧的 SO post 或 Github 要点上找到的。

<?php
function uniqueCombination($in, $minLength = 1, $max = 2000) {
    $count = count($in);
    $members = pow(2, $count);
    $return = array();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf("%0" . $count . "b", $i);
        $out = array();
        for($j = 0; $j < $count; $j ++) {
            $b{$j} == '1' and $out[] = $in[$j];
        }
        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
        }
    return $return;
}

$numbers = array(1,2,3);
$return = uniqueCombination($numbers);
sort($return);
print_r(array_map(function($v){ return implode(" ", $v); }, $return));
?>

输出:

Array (
   [0] => 1 
   [1] => 2 
   [2] => 3 
   [3] => 1 2 
   [4] => 1 3 
   [5] => 2 3 
   [6] => 1 2 3 
)

演示: https://3v4l.org/lec2F