【问题标题】:Get all possible combinations without duplicates获取所有可能的组合而不重复
【发布时间】:2017-04-28 10:06:16
【问题描述】:

如何获得给定数字的所有可能组合。 例如我有

$arr = [ 1, 2, 3, 4]

我想获得组合内没有任何重复的组合

[1] => [1]
[2] => [2]
[3] => [3]
[4] => [4]
[5] => [1, 2]
[6] => [1, 3]
[7] => [1, 4]
[8] => [2, 3]
[9] => [2, 4]
[10] => [3, 4]
[11] => [1, 2, 3]
[12] => [1, 2, 4]
[13] => [1, 3, 4]
[14] => [2, 3, 4]
[15] => [1, 2, 3, 4]

【问题讨论】:

  • 为什么你的例子停在1,2,3,4 你的逻辑说2,1,3,4 也是对的?
  • 你不是刚刚在你的例子中做了吗?
  • 你的意思是“我如何编写一个脚本来接受这些输入并产生这个输出”?否则,您已经回答了自己的问题。我会使用嵌套循环,并且在每次传递中,试试这个 in_array 函数 - php.net/manual/en/function.in-array.php
  • @JustOnUnderMillions 1, 2, 3, 42, 1, 3, 4 相同,所以是重复的
  • 然后[2, 4] 等于[4, 2](都在示例中),请在这样的问题上非常清楚!?并尝试一些并在这里展示;-)

标签: php arrays algorithm


【解决方案1】:

我希望下面的函数能按照你的预期输出:

function get_array_combination($arr) {
    $results = array(array( ));

    foreach ($arr as $values)
        foreach ($results as $combination)
                array_push($results, array_merge($combination, array($values))); // Get new values and merge to your previous combination. And push it to your results array
    return $results;
}
$set = array('1', '2', '3', '4');
$final_array = get_array_combination($set);
echo "<pre>";
print_r(array_values(array_filter($final_array))); // Removed blank entry from array and re indexing array keys.

【讨论】:

    【解决方案2】:

    我不喜欢给定的解决方案在其循环中修改迭代变量,而且我想要一个我可以轻松理解以移植到其他语言的解决方案。所以在这里:

    <?php
    function permutation(array $arr)
    {
            $out=[[]];
        
            foreach($arr as $key2=> $item2){
                $copy=$out;
                foreach($copy as $k=> $v){
                    array_push($copy[$k],$item2 );
                }
                array_push($out,...$copy);
                
            }
            
            return $out;
    }
    print_r(permutation(array(1,2,3,4)));
    
    

    为了更好地理解正在发生的事情,第二个是故意怪异的。

    <?php
    function permutation(array $arr)
    {
        
        $out=[];
        
        while(count($arr)){
            
            $out_temp=[[]];
        
            foreach($arr as $key2=> $item2){
                $copy=$out_temp;
                foreach($copy as $k=> $v){
                    array_push($copy[$k],$item2 );
                }
                if($key2==0){
                    unset($out_temp[0]);
                }
                array_push($out_temp,...$copy);
     
            }
            
            array_push($out,...$out_temp);
            array_shift($arr);
        }
    
        return $out;
    }
    print_r(permutation(array(1,2,3,4,5)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-18
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2013-10-06
      • 1970-01-01
      相关资源
      最近更新 更多