Hopefully someone can help me:
I need to write a function that can be passed a value1 and an array containing multiple numerical values.
the function then needs to be able to determine which values in the array when summed together equal the value1 passed to it.
so i guess the function could return the set of array values that could add up to value1, then return the next set, etc...
this isn't for school or anything, actually for work and would make my life a ton easier. does anyone have any ideas?
Help writing a math function
Moderator: General Moderators
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
this was a sneaky one!
outputs:
Whew! You owe me a beer
Cheers,
Kieran
Code: Select all
$parts = array(5,854,31,56,3,88,215,87,85);
$sum = '92';
function add_it_up($sum,$parts){
$results = array();
function check($sum,$parts,$so_far,&$results){
foreach($parts as $key=>$n){
if(array_sum($so_far)+$n==$sum){
array_push($so_far,$n);
//echo implode('+',$so_far).'='.$sum.'<br/>'; // testing string
$results[]=$so_far;
array_pop($so_far);
}
if(array_sum($so_far)+$n<$sum && $key!=0){
array_push($so_far,$n);
check($sum,array_slice($parts,$key),$so_far,$results);
array_pop($so_far);
}
}
}
foreach($parts as $key=>$n){
if($n<$sum) check($sum,array_slice($parts,$key+1),array($n),$results);
if($n==$sum) $results[] = $n;
}
return $results;
}
echo "<pre>";
print_r(add_it_up($sum,$parts));
echo "</pre>";Code: Select all
Array
(
[0] => Array
(
[0] => 5
[1] => 31
[2] => 56
)
[1] => Array
(
[0] => 5
[1] => 87
)
)Cheers,
Kieran