douyue8191 2017-09-21 14:28
浏览 136
已采纳

php从多维数组中获取所有有效组合

I have a array which represent allowed value in a key. The length of this array is dynamic

array(
 10=>array(100,101,102),
 11=>array(100,104),
 12=>array(100,102,103)
)

in this exemple, key 10 can have 100, 101 and 102.

I want to get all valid combination where each value appear only one time

array(
   array(10=>array(100,101,102),11=>array(104),12=>array(103)),
   array(10=>array(100,101),10=>array(104),12=>array(102,103)),
   array(10=>array(101),10=>array(100,104),12=>array(102,103)),
   array(10=>array(101),10=>array(104),12=>array(100,102,103)),
   AND SO ON
)
  • 写回答

1条回答 默认 最新

  • dongni3854 2017-09-21 17:34
    关注

    They want you to find the power sets for each index and then calculate the power set of the sets.

    This code will allows you to calculate the power set for each index. It should get you started and give you an idea of how to complete the rest of the problem.

    function power_set($arr)
    {
        $sets = [];
    
        for ($i = 0; $i < pow(2, count($arr)); $i++) {
            $set = [];
            for ($j = 0; $j < count($arr); $j++) {
                if ($i & (1 << $j)) {
                    $set[] = $arr[$j];
                }
            }
            if (count($set) > 0) {
                $sets[] = $set;
            }
            $set = [];
        }
        return $sets;
    }
    

    Output

    array(7) {
      [0] =>
      array(1) {
        [0] =>
        int(100)
      }
      [1] =>
      array(1) {
        [0] =>
        int(101)
      }
      [2] =>
      array(2) {
        [0] =>
        int(100)
        [1] =>
        int(101)
      }
      [3] =>
      array(1) {
        [0] =>
        int(102)
      }
      [4] =>
      array(2) {
        [0] =>
        int(100)
        [1] =>
        int(102)
      }
      [5] =>
      array(2) {
        [0] =>
        int(101)
        [1] =>
        int(102)
      }
      [6] =>
      array(3) {
        [0] =>
        int(100)
        [1] =>
        int(101)
        [2] =>
        int(102)
      }
    }
    

    One thing that I did notice, is that you aren't including the case where the set has no elements. Technically that should be included, so I would check to ensure that your sample output is right. I modified the algorithm to exclude this case, but I would assume that it should be included.

    If you want to include it remove the if statement that checks for the number of elements in the $set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭