代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何在PHP中找到每个子集的总和?

  •  0
  • Andrew  · 技术社区  · 6 年前

    我想计算所有可能的子集合形式数组的和。

    $array= Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 6 ); //changing
    
    function powerSet($array) {
     // add the empty set
        $results = array(array());
        foreach ($array as $element) {
            foreach ($results as $combination) {
                $results[] = array_merge(array($element), $combination);
                $total= array_sum($results); // I try this
            }
            echo $total; // I try this
        }
        return $results;
    }
    

    上面的代码用于查找子集。我是从 here . 我只是添加 array_sum 但是演示0如何查找每个子集的总数?有什么办法?

    1 回复  |  直到 6 年前
        1
  •  4
  •   dWinder Dharman    6 年前

    这个 $result 函数中是数组数组,因此不能仅使用 array_sum 关于它。为了求和您需要使用的每个子集 array_map 一起 array_sum .

    你可以在函数的末尾完成-只需添加 print_r(array_map("array_sum", $results)); 作为最后一行(如果您希望它作为输出)。

    我喜欢@splash58关于在函数外部使用它的评论:

    $ans = array_map("array_sum", powerSet($array));