0

I want to compute the sum of all possible sub-set form array.

$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;
}

The above code is used to find subsets. I found this code from here. I just add array_sum but show 0's how to find each subset total? any way ?

dWinder
  • 11,597
  • 3
  • 24
  • 39
Andrew
  • 840
  • 3
  • 17
  • 43
  • Can you explain with an example? what will be the input and output? – Bhaskar Jain Feb 04 '19 at 06:07
  • @BhaskarJain check the question upadated – Andrew Feb 04 '19 at 06:14
  • 1
    All you need to do is `$ans = array_map("array_sum", $results);` at the end of the function this will give you array of all the sum of the subset (I vote to reopen and try to edit - if you want official answer please make new (and more clearer) post) – dWinder Feb 04 '19 at 06:21
  • 1
    ^ it does not matter from where you get an array. Do it after function call. In the case `$ans = array_map("array_sum", powerSet($array));` – splash58 Feb 04 '19 at 06:24

1 Answers1

4

The $result in the function is array of arrays so you cannot just use array_sum on it. In order to sum each of the sub-set you need to use array_map together with array_sum.

You can do it in the end of the function - just add print_r(array_map("array_sum", $results)); as last line (if you want it as output).

I liked @splash58 comment about using it outside the function with:

$ans = array_map("array_sum", powerSet($array));
dWinder
  • 11,597
  • 3
  • 24
  • 39