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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器