Page 1 of 1

Help writing a math function

Posted: Mon Dec 18, 2006 4:34 pm
by kerrfowlkes
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?

Posted: Mon Dec 18, 2006 5:34 pm
by feyd
Sounds like combinatorics.

viewtopic.php?t=55043 could potentially be of interest.

Posted: Mon Dec 18, 2006 10:54 pm
by Kieran Huggins
this was a sneaky one!

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>";
outputs:

Code: Select all

Array
(
    [0] => Array
        (
            [0] => 5
            [1] => 31
            [2] => 56
        )

    [1] => Array
        (
            [0] => 5
            [1] => 87
        )

)
Whew! You owe me a beer :wink:

Cheers,
Kieran