Find numbers that equals a sum in an array

Posted by valli-R on Stack Overflow See other posts from Stack Overflow or by valli-R
Published on 2010-04-22T03:02:24Z Indexed on 2010/04/22 3:13 UTC
Read the original article Hit count: 243

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about algorithm