Reputation: 846
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 ?
Upvotes: 0
Views: 232
Reputation: 11642
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));
Upvotes: 4