【问题标题】:How to get all permutaion from a array in php?如何从php中的数组中获取所有排列?
【发布时间】:2017-02-19 19:00:04
【问题描述】:

我有一个数组

$a = array(1,2,3,4,5);

我想获取数组中$n 元素的所有组合

$n = 3

输出

1 2 3
1 3 4
1 4 5
2 3 5
2 4 5
.
.
.  
5 1 2

【问题讨论】:

    标签: php arrays permutation


    【解决方案1】:

    您基本上会在数组中从头到尾将当前数字放在开头,然后将数组的所有排列都附加到数组的开头,而不是开头的数字。如果你使用递归,那相当简单。 示例:

    input: [1] [2] [3]
    
    step 1: [1] [unknown] [unknown]
    

    现在调用用于生成所有排列的函数(此函数)并将您获得的所有数组附加到该函数中。

    每个函数调用所需的迭代次数为n!(n)*(n-1)*(n-2) ...

    【讨论】:

      【解决方案2】:

      不久前,我在日常工作(不是程序员)中遇到了类似的问题。我找到了以下代码的 javascript 版本。希望我已经对它进行了足够好的转码。我的评论。如果你能等一会(马上要去度假),那么我可以研究如何限制递归调用以减少资源占用。

      <?php
      
      function combinations($arr){
          $result = array();
          //the result array, returned by this outer function.
          function fn($active, $rest, &$a){
              if(!$active && !$rest)
                  return;//If we have empty arrays, stoppit
              if(!$rest){
                  //Are we out of remaining options? Yep, add the active array.
                  $a[] = $active;
              }else{
                  /*
                    we are currently splitting the work between the two options. First is that we compute the 
                    combinations of the currently $active and the $rest array offset by 1.
                  */
                  fn($active, array_slice($rest,1), $a);
                  $active[] = $rest[0];
                  //Next we add in the first element of the rest array to the active array, and slice off that new element to avoid duplicates.
                  fn($active, array_slice($rest,1), $a);
      
              }
          } //Function that actually does the work;
          fn([],$arr,$result);
          return $result;
      }
      
      $combos = combinations([1,2,3,4,5]);
      $combos = array_filter($combos,function($item){
          return count($item) == 2;
      });
      
      print_r($combos);
      
      ?>
      

      【讨论】:

      • 这是我在 SO 上找到的第一段代码,它实际上输出的是排列而不是组合。不过我确实有一个问题......数字 2,4,5,8,9,11,16,17,19&23 来自哪里。是否可以改为 0,1,2,3,4,5,6,7,8,9?我正在尝试弄清楚如何将其用于我正在开发的 Android 应用程序。
      猜你喜欢
      • 1970-01-01
      • 2012-04-30
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多