Find numbers that equals a sum in an array
- by valli-R
I want to find the first set of integers in an array X that the sum equals a given number N.
For example:
X = {5, 13, 24, 9, 3, 3}
N = 28
Solution = {13, 9, 3, 3}
Here what I have so far :
WARNING, I know it uses global and it is bad,that's not the point of the question.
<?php
function s($index = 0, $total = 0, $solution = '')
{
global $numbers;
global $sum;
echo $index;
if($total == 28)
{
echo '<br/>'.$solution.' = '.$sum.'<br/>';
}
elseif($index < count($numbers) && $total != 28)
{
s($index + 1, $total, $solution);
s($index + 1, $total + $numbers[$index], $solution.' '.$numbers[$index]);
}
}
$numbers = array(5, 13, 24, 9, 3, 3);
$sum = 28;
s();
?>
I don't get how I can stop the process when it finds the solution.. I know I am not far from good solution..
Thanks in advance