tags:

views:

91

answers:

1

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

+2  A: 

If your question is just how to break out of the recursion, have the function return a boolean for if it's found a match or not:

function s($index = 0, $total = 0, $solution = '')
{
    global $numbers;
    global $sum;

    echo $index;

    if($total == 28)
    {
        echo '<br/>'.$solution.' = '.$sum.'<br/>';
        return true;
    }
    elseif($index < count($numbers))
    {
        return s($index + 1, $total, $solution) or s($index + 1, $total + $numbers[$index], $solution.' '.$numbers[$index]);
    }

    return false;
}

(I left out the second part of your else since it's redundant)

Michael Mrozek
That seemed too obvious.
zipcodeman
Wow, I must be tired.. thanks.
valli-R