Romain Charles
Romain Charles

Reputation: 79

Create a recursive function with an array

I have a function but can't success to make it recursive. This is my function without recursion :

function resolution_recursion($tab1, $tab2){
    $solution = [];
    foreach($tab2 as $nb2){
        foreach($tab1 as $nb1){
            if(($nb2 + $nb1)%2 != 1){
                $solution[] = $nb2 + $nb1;
            }
        }
    }
    return $solution;
}

And I would like to make it recursive to make it work like :

$nb_ajout = [2];
$next = [[1,2],[3,4],[5,6],[7,8]];

resolution_recursion(
    resolution_recursion(
        resolution_recursion(
            resolution_recursion($nb_ajout, $next[0]),
            $next[1]),
        $next[2]),
    $next[3]);

I can't find the solution, if you can help me.

Upvotes: 0

Views: 110

Answers (2)

Romain Charles
Romain Charles

Reputation: 79

I think I have found something, not using recursion :

function resolution_recursion($tab1, $tab2){
    $solution = [];
    $solution[-1] = $tab1;
    foreach($tab2 as $key => $tab){
        foreach($tab as $nb2){
            foreach($solution[$key-1] as $nb1){
                if(($nb2 + $nb1)%2 != 1){
                    $solution[$key][] = $nb2 + $nb1;
                }
            }
        }
    }
    return $solution;
}

Upvotes: 0

zanderwar
zanderwar

Reputation: 3730

Something like this would do the trick...

function resolution_recursion($tab1, $tab2, $solution = [])
{
    if (empty($tab2)) {
        return $solution;
    }
    
    $set = array_shift($tab2);
    
    foreach($set as $nb2){
        foreach($tab1 as $nb1){
            if(($nb2 + $nb1)%2 != 1){
                $solution[] = $nb2 + $nb1;
            }
        }
    }

    if (!empty($tab2)) {
        return resolution_recursion($tab1, $tab2, $solution);
    }

    return $solution;
}

You can find a demo here (the output however means absolutely nothing to me though so hopefully it means something to you lol)

Upvotes: 1

Related Questions