0

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.

4
  • why? if you can make it iterative, you win aahah recursion is very very heavy Commented Jan 13, 2021 at 12:03
  • Actually that function is very simplified and I will have to use arrays with variable depths that I won't know the depth in advance Commented Jan 13, 2021 at 12:06
  • 2
    It would greatly help if you could explain what the function should do in detail and provide some inputs with the corresponding desired outputs. "I can't find the solution" - show us what you tried. Commented Jan 13, 2021 at 12:13
  • I think I have found something, I will come back to you if my problem is not resolved. Thank you Commented Jan 13, 2021 at 12:41

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.