Struggling to grasp Recursion in JavaScript - javascript

Right now I'm going through Codecademy's recursion track and I'm confused how to interpret this correct code.
// Create an empty array called "stack"
var stack = []
// Here is our recursive function
function power(base, exponent) {
// Base case
if ( exponent === 0 ) {
return 1;
}
// Recursive case
else {
stack[exponent-1] = base * power(base, exponent - 1); //confused by start of this line
return stack[exponent-1];
}
}
power(3,3)
console.log(stack) // [3,9,27]
If exponent-1 becomes 2 then 1 then 0, why does 3 become the element at the 0th position in the array rather than at the 2nd position (and so on) ?
I'd really appreciate any help.

On the first pass, exponent is 3, so you will store a value at stack[2]. But that value is not calculated until the recursive call has completed with power(3,2)...power(3, 1).
So the assignment to stack[3-1] is preceded by the one to stack [3-2], which in turn is preceded by the one to stack[3-2]

Notice that there are four different exponents in the execution of this call, one in each scope of the power invocation.
call power(3, 3)
exponent' = 3
is not 0
calls power(3, 2)
exponent'' = 2
is not 0
calls power(3, 1)
exponent''' = 1
is not 0
calls power(3, 0)
exponent'''' = 0
is 0
returns 1
multiplies the return value by 3
assigns it to stack[exponent'''-1]: stack[0] = 3
returns 3
multiplies the return value by 3
assigns it to stack[exponent''-1]: stack[1] = 9
returns 9
multiplies the return value by 3
asigns it to stack[exponent'-1]: stack[2] = 27
returns 27
logs the value of stack
Indeed the stack is built "backwards", after returning from the recursive calls, not before entering them. If you want to have a better representation of the call stack, you can try to add
callstack.push(exponent);
in the first line of your function body. After the execution of your script, the callstack would look like [3, 2, 1, 0] as you might have expected.

It helps if you write it out in a table:
power(3, 3) stack[2] = 3 * power(3, 2)
power(3, 2) stack[1] = 3 * power(3, 1)
power(3, 1) stack[0] = 3 * power(3, 0)
power(3, 0) return 1
Then substitute the values:
stack[0] = 3 * 1
stack[1] = 3 * 3
stack[2] = 3 * 9

Related

Trouble with recursive functions

Can anyone explain this to me? I'm having trouble wrapping my head around this concept of having function within a function.
function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num-1);
}
factorialize(10);
This is not a loop right? Why does the function call itself continuously? How does it know when to stop? Wouldn't it just continue to factorialize negative numbers to infinity?
Appreciate the help and guidance as always.
This is not a loop right?
Nope, it is not. It is a recursive function, a function that calls itself until a certain condition is met. In this case, is when num is equals to 0.
Why does the function call itself continuously?
Because the function is called in the return value of this function. It will continue calling the function itself, until num equals 0. In which case the function will exit and return 1.
How does it know when to stop?
The condition if (num === 0). The variable num gets subtracted if num isn't equal to 0 as stated in the code return num * factorialize(num-1);. Notice that the function returns fresh function call but with the parameter num - 1. When num becomes 0. The function returns 1.
Wouldn't it just continue to factorialize negative numbers to
infinity?
Because we have this if (num === 0) condition. So the num parameter decreases each time the code return num * factorialize(num-1); gets called, and eventually the above condition gets fulfilled and the function exits.
We can break it down step by step:
factorialize(10) gets called.
num is not 10, so return num * factorialize(num - 1). In this case num is 10 and num - 1 is 9, so we are actually returning the following: 10 * factorialize(10 - 1).
factorialize(9) gets called, then repeat step (1) and (2) until you get factorialize(0).
When you reach factorialize(0), it will return 1. So the whole function effectively returns 10 * 9 * 8 * ... 1 * 1.
Makes sense?
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. You can read about it here
Lets visualize:
factorialize(10)
10*factorialize(9)
9*factorialize(8)
8*factorialize(7)
7 *factorialize(6)
6 *factorialize(5)
5 *factorialize(4)
4 *factorialize(3)
3 *factorialize(2)
2 *factorialize(1)
1 *factorialize(0)
1 (if num==0 return 1)
1
2
6
24
120
720
5040
40320
362880
3628800
Hope this helps!
Each time the function "factorialize" runs your argument "num" get decremented by
1. So num will run from 10 to 1 and when 1 is returned it will reach its terminal case 0. It is only terminal because of your "if" clause ( your base case ) when num === 0, you return 1, and your recursive "factorizlize" is never reached, so it is never executed.
I am not really good with analogies. However, If it still doesn't make sense let me know.
Every iterative problem can be solved by using recursion. try to look at this code
var start = 1;
var end = 10;
var increment = 1;
document.write("loop output: ")
for(var num = start; num <= end; num = num + increment){
document.write(num);
document.write(" ");
}
document.write("\n function output:\n")
function iteration(num) {
//stop condition statement
if (num > end) {
return 1;
}
// inside code block
document.write(num);
document.write(" ");
//incremention
iteration(num+increment);
}
iteration(start);
It uses internal functional frame stack for recursion purpose. for more about recursion look here . little practice is need to understand this concept.Hope make sense. Happy Coding !

Need some help to understand recursion

I am trying to understand, how recursion works. I got the basic idea, but the details remain unclear. Here is a simple example in javascript:
function sumTo(n){
if (n > 1){
return n + sumTo(n-1)
} else {
return n
}
}
sumTo(3);
It is supposed to count all numbers in 3 and the result is 6 (1 + 2 + 3 = 6), but I don't get, how it works.
OK, we start from if condition. 3 > 1, so we return n and call the function again, but what will be inside if brackets?
Does it look like this:
3 + sumTo(2) // 3 - 1 = 2
Or we don't do anything with n, and wait for the next function:
3 + sumTo(n - 1) // n will come later
I was told that the last function will return 1 to the upper one, but I don't get what it will do with this 1.
If there is some step-by-step explanation for ultimate dummies, please share.
I know there is a lot of similar questions, but found no help.
UPD: It looks like I finally found out how it works, spending two days and asking everyone I could. I'll try to explain for ultimate dummies like me. That's gonna be long, but I hope somebody with the same troubles will find this post and it will be useful.
At first I'd like to show another example of recursion, which is a little easier. I found it at http://www.integralist.co.uk/posts/js-recursion.html and changed values from (1, 10) to (2, 3).
function sum(x, y) {
if (y > 0) {
return sum(x + 1, y - 1);
} else {
return x;
}
}
sum(2, 3);
When we start the function, we check the if condition y > 0. Y is 3, so the condition is true. So we return sum(x + 1, y - 1), i. e. sum(2 + 1, 3 - 1), i. e sum(3, 2).
Now we need to count sum(3, 2). Again, we go to the beginning and start from condition y > 0. Y is 2, so the condition is true. So we return sum(x + 1, y - 1), i. e. sum(3 + 1, 2 - 1), i. e sum(4, 1).
Now we need to count sum(4, 1). One more time, we check the condition y > 0. Y is 1, the condition is true. We return sum(x + 1, y - 1), i. e. sum(4 + 1, 1 - 1), i. e sum(5, 0).
Now we need to count sum(5, 0). We check the condition y > 0 and it is false. According to the if-else in the function, we return x, which is 5. So, sum(2, 3) returns 5.
Now let's do the same for sumTo();
function sumTo(n){
if (n > 1){
return n + sumTo(n-1)
} else {
return n
}
}
sumTo(3);
Starting from sumTo(3). Checking the n > 1 condition: 3 > 1 is true, so we return n + sumTo(n - 1), i. e. 3 + sumTo(3 - 1), i. e. 3 + sumTo(2).
To go on, we need to count sumTo(2).
To do this, we again start the function from checking the n > 1 condition: 2 > 1 is true, so we return n + sumTo(n - 1), i. e. 2 + sumTo(2 - 1), i. e. 2 + sumTo(1).
To go on, we need to count sumTo(1).
To do this, we again start the function and check the n > 1 condition. 1 > 1 is false, so, according to if-else, we return n, i. e. 1. Thus, sumTo(1) results in 1.
Now we pass the result of sumTo(1) to the upper function, sumTo(2), where we earlier stated that we needed sumTo(1) to go on.
SumTo(2) returns n + sumTo(n-1), i. e. 2 + sumTo(2 - 1), i. e. 2 + sumTo(1), i. e. 2 + 1. Thus, sumTo(2) results in 3.
Now we pass the result of sumTo(2) to the upper function, sumTo(3), where we earlier stated that we needed sumTo(2) to go on.
SumTo(3) returns n + sumTo(n-1), i. e. 3 + sumTo(3 - 1), i. e. 3 + sumTo(2), i. e. 3 + 3. Thus, sumTo(3) finally results in 6. So, sumTo(3) returns 6.
My mistake was that everywhere I tried to insert 3 instead of n, while n was decreasing to 1.
Thanks to everyone, who responded to this question.
You can understand like
sumTo(3);
returns => 3 + sumTo(2) // n is greater than 1
returns => 2 + sumTo(1)
returns => 1 // 1 as n is not greater than 1
That's right, sumTo(n) waits until sumTo(n-1) is completed.
So, sumTo(3) waits for sumTo(2),
sumTo(2) waits for sumTo(1),
then sumTo(1) returns 1,
sumTo(2) returns 2 + 1
and sumTo(3) returns 3 + 2 + 1
Showing work:
sumTo(4) = (4 + 3) + (2 + 1) = 10 // 4 + sumTo(3). function called four times
sumTo(3) = (3 + 2) + 1 = 6 // 3 + sumTo(2). called three times
sumTo(2) = (2 + 1) = 3 // 2 + sumTo(1). called twice
sumTo(1) = (1) = 1 // called once
It will probably be easier for you to wrap your head around if you think of it backwards, from the ground up instead of from the top down. Like this:
sumTo(1) = 1 + sumTo(0) = 1
sumTo(2) = 2 + sumTo(1) = 3
sumTo(3) = 3 + sumTo(2) = 6
sumTo(4) = 4 + sumTo(3) = 10
Notice how now you can keep adding to the list, and it will be easy to calculate the previous one because you're just adding the two sums.
The chain of events is as follows:
sumTo(3) adds 3 and calls sumTo(2) which also calls sumTo(1) and returns 3, giving you a grand total of 6.
Does that make sense? I'll gladly elaborate or clarify if anyone has questions.
An important question to understand is why to use recursion and when to use recursion. A good discussion on the subject can be found here: When to use recursion?
A classic example of recursion is the fibonacci sequence. Another good example would be traversing a directory of files on your computer, for example if you wanted to search every file inside of a folder that contains other folders. You can also use recursion to factor exponents.
Consider an easier example of recursion:
function multiplyBy10(i) {
if ( !i ) return 0;
return 10+multiplyBy10(i-1);
}
This function will multiply the number by 10 using recursion. It's good to get a grasp on when recursion is practical because there are times it makes things easier for you. However, it's best to keep things simple and not confuse yourself wherever possible. :)

Can you explain how this Factorial function works?

I understand that "a" solution is:
function Factorial(number)
{
if(number == 0 || number == 1){
return 1;
}
return number * Factorial(number -1);
}
I want to understand what exactly is going on. I understand what is going on all the way to the last part when number == 1.
If we were to take a simple example of say 3!
3 is not equal to 0 or 1 so we return 3 * Factorial(2)
2 is not equal to 0 or 1 so we return 2 * Factorial(1)
1 is equal to 1 so we return 1
How do we know when to stop? Is it the fact that we return 1 that tells the function to stop?
If that is the case, why does the function not stop when we first return 3 * Factorial(2)? Is it because it's returning a function so that it must continue until it no longer returns a function?
Thank you
I think you have to understand the logic of factorial.
So factorial is just products, indicated by an exclamation mark ie, if you write
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1
Hope you find the pattern, so you can write the above factorials as:
0! = 1
1! = 1
2! = 2*1!
3! = 3*2!
4! = 4*3!
5! = 5*4!
So in your function you are using the similar logic.
Now in your function
if(number == 0 || number == 1)
{
return 1;
}
The above logic is to cover the first two cases i.e, 0! and 1! And
return number * Factorial(number -1);
is for the rest of the numbers.
So you are using the recursive technique of solving the factorial problem.
To understand recursion, lets take a number say 5 i.e., we want find the value of 5!.
Then first your function will check
if(number == 0 || number == 1)
which is not satisfied, then it moves to the next line ie,
return number * Factorial(number -1);
which gives
5*Factorial(5-1) which is equal to 5*Factorial(4)
Now on subsequent calls to your Factorial function it will return the value like below:
5*(4*Factorial(4-1)) which is equal to 5*(4*Factorial(3))
5*(4*(3*Factorial(3-1)) which is equal to 5*(4*(3*Factorial(2)))
5*(4*(3*(2*Factorial(2-1)))) which is equal to 5*(4*(3*(2*Factorial(1))))
Now when it returns factorial(1) then your condition
if(number == 0 || number == 1)
is satisfied and hence you get the result as:
5*4*3*2*1 = 120
On a side note:
Beware that factrial is used only for positive integers.
Recursion relies on what is called a base case:
if(number == 0 || number == 1){
return 1;
}
That if statement is called your base case. The base case defines when the recursion should stop. Note how you are returning 1 not returning the result of a call to the function again such as Factorial(number -1)
If the conditions for your base case are not met (i.e. if number is NOT 1 or 0) then you proceed to call the function again with number * Factorial(number - 1)
If that is the case, why does the function not stop when we first return 3 * Factorial(2)?
Your simple example of 3! can be elaborated like this :
return 3 * Factorial(2)
will then be replaced by
return 3 * (2 * Factorial(1))
which then will be replaced by
return 3 * (2 * 1) // = 6 Hence 6 is returned at last and recursion ends.
How do we know when to stop?
When all your Factorial(value) is replaced by a returned value we stop.
Is it the fact that we return 1 that tells the function to stop?
In a way, yes. Because it is the last returned value.
It is called recursion.
This function is called like this
var result = Factorial(3);
in Factorial function
First time
return 3*Factorial(2);
Now here return statement doesnt get executed insted Factorial is called again..
so second time
return 2*Factorial(1);
again in Factorial(1)
Third time
return 1;
So go to second
return 2*1;
Next to first
return 3*(2*1);
Finally
var result = 3*2*1 = 6.
The function is recursing (calling itself) - and taking one from "number" each time.
Eventually (as long as its a positive integer you call it with, otherwise you'll probably get an infinite loop) you'll always hit the condition (number == 1) so instead of recursing further, it'll return 1 rather than call the function again.
Then, once you have hit the bottom (1), it'll start to run the function and work back up the other way along the function call stack, using the previous result each time:
1 = 1
(2*1) = 2
(3*2) = 6
(4*6) = 24
etc
So the final return statement from the function will return the required result

How does Eloquent JavaScript recursion example terminate as return 1 but still output exponential value

In the code below I understand exactly how it works, right up until the termination and the 'return 1'. I would assume that once the function terminates it should output 1 but instead it does what you would expect an exponential program to do, it outputs the correct answer which in this case is 9.
My question is why is this so ?
I assume the way I visualize recursion is incorrect ( maybe my idea of how the stack treats recursion ?) I found a similar question to mine here but it doesn't help this one granular little inking of my understanding.
function power(base,exponent){
if(exponent === 0){
return 1 // Terminates with return 1 but output is correct
}
return base * power(base, exponent-=1);
}
power(3,2) // This outputs 9 not 1. Why?
The recursive function works like this:
At first, The function will return 3 * power(3, 1).
Now you are only invoking the function at the right hand side, so only that value must resolve so it will become.
3 * 3 * power(3,0)
Again only the right most part is a function which must resolve.
So it will be:
3*3*1
No more function is there to resole, so the first function provides you the result as 9.
it's similar to
var x = multiple(3,1) * multiple(3,2) * multiple (3,4);
Now all those functions will execute from left to right.
So once all functions are resoled, the value of x will be calculated.
For a recursive algorithm there must be at least one base case; the recursion will eventually reach the base case. Your base case is 1, then base * power(base, exponent-1) recurses until it hits the base case, at which point it will leave you with return base * 1, which is base, then the stack will unravel, until it returns the result.
To visualize the recursion for power(3, 3) you can write the process going down first:
3 * power(3, 2)
3 * power(3, 1)
3 * power(3, 0)
Now go up and replace the recursive calls starting at the base case (last line).
3 * power(3, 2)
3 * power(3, 1)
3 * power(3, 0) = 3 * 1 = 3
// we know power(3, 0) = 1; this is the base case
Now carry up the results to do the same for the rest, until you get the final value:
3 * power(3, 2) = 3 * 9 = 27
3 * power(3, 1) = 3 * 3 = 9
3 * power(3, 0) = 3 * 1 = 3

What is the variable result doing in this javascript function

In the code below, if result is set to one, the code returns a number 1024 (2 to the power of 10). If result is set to 2, the code returns the number 2048 (or 2 to the power of 11), BUT if result is set to 3, the code doesn`t return the number 4096 (as I would expect, because 2 to the power of 12) but rather 3072. Why does it return 3072 if "result" is set to 3, but otherwise if set to 1 and 2 it followers the pattern of power to the 10th and 11th
function power(base, exponent) {
var result = 1;
for (var count = 0; count < exponent; count++)
result *= base;
return result;
}
show(power(2, 10));
In this code, result is used as an accumulator. The code computes result * base**exponent; result is not part of the exponent.
I think you're confusing yourself. The thing being raised to some power is your first parameter (in your example 2). The exponent is the 2nd parameter (10). Your example works correctly. Pass in 12 as your exponent and you will see your expected result.
The result parameter is just a place holder in which you accumulate your results (2x2x2x2....)
The numbers doing all the work are the ones you pass in as parameters to the function.
So, in your example, you're going to take 2 and multiply it by itself 10 times, each time storing the cumulative result in the variable "result". The thing that's throwing you off is that result is initially set to 1. This is never meant to be altered. It's built that way so that if you set your exponent to 0 you will end up with a result of 1 (because any number raised to the zeroth power = 1).
Anyway... don't worry about what result is set to. Focus on how the loop works with the interchangeable variable values that are being passed in, in the function call.
Do out the multiplication:
3 * 2 = 6
6 * 2 = 16
12 * 2 = 24
24 * 2 = 48
48 * 2 = 96
96 * 2 = 192
192 * 2 = 384
384 * 2 = 768
768 * 2 = 1536
1536 * 2 = 3072
Multiplication table perhaps? Also, what's wrong with Math.pow, just trying to accomplish it yourself?

Categories

Resources