Tell us what’s happening:
In the explanation n is decreasing but the final array values are increasing and I don’t understand why. Could anyone please explain it to me.
Thanks
Your code so far
// Only change code below this line
function countdown(n){
return;
}
// Only change code above this line
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.
function russianDoll
{
//Base case If this falls then ->
if (we found the piece of chocolate)
return "yummy";
// -> it call's toward itself
else if
russianDoll(smallerDoll)
//but what if there is no chocolate or a smaller doll
else (no more dolls)
return "No chocolate here "
We basicly have conditions that check over itself
In recursion we use a factorial number which is basicly like this
4!
4 * 3 * 2 * 1
24
Now if we want to write it out in code it would be
function factorialNumber(n)
{
if (n == 1 || n == 0)
return 1; //just like the chocolate this is or base case
else return n * factorialNumber(n -1)
}
console.log( factorialNumber(4)) //this returns 24
now what happens is the next:
1st it checks over the base case but since thats not the case since 4 != 0|| 1
so it runs the next part of our code
4* factorialNumber(4-1 which sums up to 3)
then it does the same so we get
4* factorialNumber( 3)
3* factorialNumber( 2)
2 now 2 is the value of factorialNumber( 2) so it bubbles up
3 * 2 = 6 which is the value of 3 so it bubbles up again
same thing repeats and we are left with the value of 24
Did had help from YouTube so i don't own any credits for this
I found that the following solution allowed me to understand the concept a bit easier as it is a bit easier for me to step through what the function is doing (click to unblur).
Note I used countup here instead of countdown as it demonstrates the concept a little better. There is only one thing you need to switch to make it work for countdown, which you will probably work out straight away.
solution here
function countup(n) { if (n < 1) { return []; } else { return [...countup(n - 1), n]; } }
If you run through it with an n of 5, you can follow what it is doing like so:
create an array with 5 in last place
what goes before the 5 in the array? Call the function again with 4 and spread the result of that function in the same array (with the ... notation)
now 4 is in last place within its recursive step, but is in second last place overall because of the spread operator
what goes before the 4 in the array? As before, call the function again with 3 and then spread the result of that function in the same array
repeat until you reach your base case
return your array
Hopefully that helps someone and doesn’t confuse things any further!