Help writing a math function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kerrfowlkes
Forum Newbie
Posts: 1
Joined: Mon Dec 18, 2006 4:29 pm

Help writing a math function

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Sounds like combinatorics.

viewtopic.php?t=55043 could potentially be of interest.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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
Post Reply