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 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路