【问题标题】:How can I get all possible combinations of element in set? (power set) [duplicate]如何获得集合中元素的所有可能组合? (电源组)[重复]
【发布时间】:2019-05-31 09:17:15
【问题描述】:

我有一个数字数组:

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

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

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

我怎样才能做到这一点?

【问题讨论】:

标签: php arrays combinations formula permutation


【解决方案1】:

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

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进行编辑

【讨论】:

  • 干净整洁。谢谢。
  • 这段代码有错误吗?对comb() 的调用是否应该是对powerSet() 的调用?
  • @MikeSchinkel - 你是对的 - 可能在一次编辑中迷路了......已修复。谢谢!
  • @dWinder — 谢谢你的回答,顺便说一句。正是我正在寻找的东西,因为它是一个脑筋急转弯我不想弄明白的东西。
【解决方案2】:

部分解决:

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

【讨论】:

    【解决方案3】:

    可能是我在旧的 SO 帖子或 Github gist 上找到的。

    <?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

    【讨论】:

    猜你喜欢
    • 2010-10-02
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多