Can some one explain me the following Java snippet for recursion? - java

public class GetElementWithoutPop {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
System.out.println("stack is " + stack);
// Using Java
int position = 3;
Integer result = stack.get(position);
System.out.println(result);
}
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}
}
Till the index becomes 0 from 3 it's all good and simple, but after that the code goes back to try block and then again to finally block and the index starts to increase on its own all the way back to 3 and stack.push(x) brings the stack back to its original state.
How is this happening?
Fairly new to recursions & I need to understand this!

This happens because each function call has its own unique context for the same function so the variable x stores the popped variable and calls recursively to pop further value but that value is stored in x of the next function call, while returning the finally block runs and each unique value of x in each function call is again pushed
T x = stack.pop(); // this value remains stored in the function call stack
try {
return getStackElement(stack, index - 1); // same function runs for further case (n-1) th and stores the value in its own x variable in its context
} finally {
stack.push(x); // after the control returns, this copy of function has its unique x variable and that is pushed again
}
You mention that "index starts to increase on its own all the way back to 3 .." that's because each function call has its own set of variables including index
Some Steps
1) Function call instance with index 3 calls function with index 2
2) Function call instance with index 2 calls function with index 1
3) Function call instance with index 1 calls function with index 0
4) Control returns
5) Now the control is back to instance with index value 1
6) Control returns from even that instance and now is back to instance with index 2
This is like winding and then unwinding,, while solving problems with recursion we have to often decide whether we want to do some work at call for n and then call for n-1 OR call for n-1 , let the control return and then do some work

Related

Recursive solution to counting the number of ways you can go up a staircase

I'm trying to solve the problem of "count ways to reach the nth step in a staircase" with recursion. When given a number of stairs to climb, I have to calculate the number of ways to climb taking either 1 or 2 steps at a time. For example, if there are 4 stairs, we would return 5 since we would have:
* 1 1 1 1
* 1 1 2
* 1 2 1
* 2 1 1
* 2 2
My code is currently throwing a stack overflow exception:
public static int countWaysToClimb(int stairs) {
return countWaysToClimbHelper(stairs, 0, 0);
}
public static int countWaysToClimbHelper(int sumNeeded, int currentSum, int possibleCombos) {
// base - we will reach this base multiple times
if (sumNeeded == currentSum) {
possibleCombos++;
// if we already found a combo, we need to reset the sum
countWaysToClimbHelper(sumNeeded,0,possibleCombos);
}
else if (currentSum > sumNeeded) {
return 0;
}
// recurse - add 1 and then add 2
countWaysToClimbHelper(sumNeeded,currentSum+1,possibleCombos);
countWaysToClimbHelper(sumNeeded,currentSum+2,possibleCombos);
return possibleCombos;
}
Thank you!
There are some issues in your code:
Base case (condition that terminates the recursion) is incorrect. Every branch of recursive calls spawn new branches when it hits the condition if (sumNeeded == currentSum) is meat instead of returning the number of combinations. You created an infinite recursion that inevitably leads to a StackOverflowError. You have to place a return statement inside the curly braces after the first if in your code. And comment out the first recursive call (with 0 sum passed as an argument) you'll face the second problem: for any input, your code will yield 0.
Results returned by recursive calls of your method countWaysToClimbHelper() are omitted. Variable possibleCombos isn't affected by these calls. Each method call allocates its own copy of this variable possibleCombos on the stack (a memory aria where JVM stores data for each method call), and their values are not related anyhow.
you actually don't need to pass the number of combinations as a parameter, instead you have to return it.
Before moving further, let me recap the basics of recursion.
Every recursive method should contain two parts:
base case - that represents a simple edge-case for which the outcome is known in advance. For this problem, there are two edge-cases:
sumNeeded == currentSum - the return value is 1, i.e. one combination was found;
sumNeeded > currentSum - the return value is 0.
recursive case - a part of a solution where recursive calls a made and when the main logic resides. In your recursive case you need to accumulate the value of the number of combination, which will be the sum of values returned be two branches of execution: take 1 step or 2 steps.
So the fixed code might look like that:
public static int countWaysToClimb(int stairs) {
return countWaysToClimbHelper(stairs, 0);
}
public static int countWaysToClimbHelper(int sumNeeded, int currentSum) {
// base - we will reach this base multiple times
if (sumNeeded == currentSum) {
return 1;
} else if (currentSum > sumNeeded) {
return 0;
}
// recurse - add 1 and then add 2
int possibleCombos = 0;
possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 1);
possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 2);
return possibleCombos;
}
Note:
This code could be enhanced further. The whole logic can be implemented inside the countWaysToClimb() without using a helper-method. For that, instead of tracking the currentSum you need to subtract the number of steps from the sumNeeded when the method is called recursively.

My codes give an exception while using recursive function

i am trying to print numbers from 1 to 10 without using loops in java. When n+1 is passed to recursivefun method call in line 6,it works fine. But when n++ is passed,the code throws an error :/
public class PrintWithoutUsingLoops {
public static void recursivefun(int n) {
if (n <= 10) {
System.out.println(n);
recursivefun(n++);//an exception is thrown at this line.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
recursivefun(1);
}
}
recursivefun(n++);
passes the original value of n to the recursive call (since you are using the post-increment operator), making this recursion infinite (since each recursive call gets the same value of n, which never reaches 11) and leading to StackOverflowError.
Change it to
recursivefun(n+1);
or
recursivefun(++n);
recursivefun(n++);
is a call with post-increment. Post increment is a mechanism which enlarges the value after it is read. In this case, you always pass 1.
You can use pre-increment which is ++n which first: increments and then passes the value.
The exception you get is StackOverflowError which means, that the stack is full and JVM cannot store more calls on stack, so it won't be able to revert.
recursivefun(n++);
This line means : call recursivefun(n); and then increment n by 1 so you'll always call your fuction with n=1 and caused a stackOverflow sure
So you need to increment n BEFORE all the function, you have some options :
recursivefun(n+1);
//-----------------------------
n++;
recursivefun(n);
//-----------------------------
recursivefun(++n); //pre-cincrement
Indeed both post and pre increment operators increments the value of a variable. Their behavior changes based on the context of the usage. Assume the following code:
For loop 1:
for (i=0; i<10; i++)
...
For loop 2:
for (i=0; i<10; ++i)
...
In both of the above statements, the for loop iterates 10 times irrespective of the increment style used. However consider the following code:
int x = 10;
int y = 20;
int z = x++ + ++y; // z = 10 + 21
System.out.println("x = " + x); // prints 11
System.out.println("y = " + y); // prints 21
System.out.println("z = " + z); // prints 31
Hence from your code it is evident that
recursivefun(n++);
calls recursivefun with argument 1 infinitely. To avoid StackOverFlow error use either ++n or n+1.

recursive function called with different values

I have a recursive function like this:
public static int h(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
//variable value is a fixed one.
i = value % 2;
return h(n - h(i) - 1) + h(n - 2);
}
}
Suppose the value of variable value is even at this time.Then if I call the function with h(12) I want to know how the function works?
In this case what I want to happen is evaluate
h(12)=h[12-h(0)-1]+h(10)
=h(11)+h(10)
={h(11-h(0)-1)+h(9)}+{h(10-h(0)-1)+h(8)}
={h(10)+h(9)}+{h(9)+h(8)}
Here when evaluating h(11)+h(10) does the function first finish h(11) and get a value for that before starting with h(n-2) which is this case h(10).
If it first finish h(11) then finally it has to reach n==0 or n==1 case.Then by the time it reaches wouldn't h(n-2) be h(-2) or h(-1).
How can I store the initial function call value of 12 and when it reaches h(n-2) to call as h(10) and then make that part to evaluate as h(8),h(6)..
Each function call stores its own copy of arguments. So, call to h(11) won't change n in the first call (h(12)).
Expressions in Java are evaluated from left to right. This means that the call h(11) would finish before h(10) is called from h(12). However, in this case this is not important, since the result would be the same either way.

How to understand the concept of recursion in java?

I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.
package javaapplication1;
public class JavaApplication1 {
static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.
http://i.stack.imgur.com/pjqJy.png
A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function.
Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120.
it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4!
Take into consideration that 0! = 1.
to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial.
Further more, explaining your code, let us calculate Factorial(5):
Factorial() returns an integer.
Initial Call from main(): 5 != 0, then skip the condition (n == 0); t
= Factorial(5-1) = Factorial(4);
Second call from Factorial(4): 4 != 0, then skip the condition (n ==
0); t = Factorial(4-1) = Factorial(3);
Third call from Factorial(3): 3 != 0, then skip the condition (n ==
0); t = Factorial(3-1) = Factorial(2);
Fourth call from Factorial(2): 2 != 0, then skip the condition (n ==
0); t = Factorial(2-1) = Factorial(1);
Fifth call from Factorial(1): 1 != 0, then skip the condition (n ==
0); t = Factorial(1-1) = Factorial(0);
Sixth call from Factorial(0): 0 == 0, then return value 1;
First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1
= return value 1;
Second return, 1, to Fourth call (Factorial(2)): return n*t = return
2*1 = return value 2;
Third return, 2, to third call (Factorial(3)): return n*t = return 3*2
= return value 6;
Second return, 6, to second call (Factorial(4)): return n*t = return
4*6 = return value 24;
Second return, 24, to First call (Factorial(5)): return n*t = return
5*24 = return value 120;
Second return, 120, to Initial call (from main()): print(120);
Hope this helps you understand recursion.
When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.
When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.
Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:
If a parameter meets a terminating condition, return (usually a result)
Else adjust parameters for the next iteration and call self
The code your teacher wrote has some style issues. It would be clearer if written like this:
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)
I would write it like this, eliminating the if altogether:
static int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
When one knows that a task can be broken into similar smaller tasks ,then we use recursion or calling the same method(until we met a certain condition).Recursion not only helps in execution of a problem without having to define or invoke another method,it also helps in visualizing a pattern by which the task is getting executed
Personally, I do not like the factorial problem. I find it hard to understand and I do not think it explains recursion in a clear way. So lets look at a different example. Lets say that we want to print numbers from 1-100. This is a very simple task with a for loop and a counter, but it can also be done with recursion. For example:
public static void main(String[] args) {
numbersAscending(1);
numbersDescending(1);
}
//Prints 1 2 3 ... 100
public void numbersAscending(int x){
System.out.println(x);
if(x < 100){
numbersAscending(x+1);
}
}
//Prints 100 99 98 ... 1
public void numbersDescending(int x){
if(x < 100){
numbersDescending(x+1);
}
System.out.println(x);
}
When a function is called, that call goes on top of the stack. Think of this like a stack of cards. Each one has a number on it (1-100). When a function calls itself, a new card gets added to the stack. When the function finishes, it is taken off of the stack.
So for the example above, every time numbersAscending is called, it prints out the current value for x before calling that function again. This results in the numbers being printed in order from 1-100. As soon as 100 is reached, it stops calling itself and pops each function off of the stack.
On the other hand, every time numbersDescending is called, it calls itself again before printing out the number. In this way, x doesn't start printing until it reaches 100. It then moves back down the stack, printing each number as it goes back to the main method.
/*This program in java will help you to understand all the basics of
recursion:
->how control flows in recursion
->how return is executed in the recursive functions
->how and when the statements after recursive function area executed.*/
public class Understanding_Rec{
public static int rec(int x)
{
if(x<5)
{
System.out.println("-->Smaller than 5");
rec(x+1);
System.out.println("<--After recursion inside x<5");
return x;
}
else if(x<7)
{
System.out.println("-->Smaller than 7");
rec(x+1);
System.out.println("<--After recursion inside x<7");
}
System.out.println("<--No Condition Statement");
return x;
}
public static void main(String[] args)
{
int x=1;
rec(x);
System.out.print(x+"Inside main");
}
}
I am not sure if it explains, but if you had a precalculus class then you should know that factorial can be defined in two waqys.
n!=1*2*...*n
of we define
1!=1
and
n!=n*(n-1)!
Try to see yourself that those definitions are equivalent. Pick let us say, 5!
according to second definition
5!=5*4!
but 4!=4*3! so 5!=5*4*3!
but 3!=3*2! so 5!=5*4*3*2!
and so on. Keep doing it until you hit 1!. But 1!=1 so you stop.
Recursion in programming is the same thing.
TomW

Counting in recursion calls

I need to write a method that checks how many possible ways there are to finish a grid (a 2D array).
the movement inside the grid is like this:
start with [0][0] take the number inside there (for instance 14) then go to either
[array.[0][0]%10][array.[0][0]/10] or [array.[0][0]/10][array.[0][0]%10]
for our example:
[1][4] or [4][1]
until you get to the end of the array (bottom right corner).
I can get to the end of the array (all possible ways) - my problem is to count how many times I actually finished the array - I can not use a variable outside of the method, and the method has to be recursive.
this is the code :
private static int howMany(int[][] array, int y, int x, int count) {
if(y+(array[y][x]%10) < array.length && x+(array[y][x]/10)< array[y].length && array[y][x]!=0) {
System.out.println("["+y+"]["+x+"] is: "+array[y][x]);
howMany(array, y+(array[y][x]%10), x+(array[y][x]/10),count);
}
if(y+(array[y][x]/10) < array.length && x+(array[y][x]%10)< array[y].length && array[y][x]!=0) {
System.out.println("["+y+"]["+x+"] is: "+array[y][x]);
howMany(array, y+(array[y][x]/10), x+(array[y][x]%10),count);
}
if(y==array.length-1 && x==array[y].length-1) count++;
return count;
}
this is obviously wrong and will return what count was in the first place, I tried many other ways but to no avail...
here's the full class (with an array to test):
link to full class
edit: a big Thanks to everyone for their help!
The count is already returned from each call to howMany. I think you just need to save it:
count = howMany(array, y + (array[y][x] % 10), x + (array[y][x] / 10), count);
Do this inside both if blocks. I made this change in your linked code and got the expected result (3).
You are already on the right track, since your method signature returns an int. You should define a variable to hold the count, increment it for the primary recursive call, and add to it the result of the recursive method itself. Passing the count into the each recursive call is unnecessary and should be removed.
Return 1 if you've reached the end of the array (bottom right corner) and 1+howMany(array, newY, newX) otherwise. You don't need to keep the count and pass it every time. The function will work so:
1 + returned value of 2nd call =
1 + 1 + returned value of 3rd call =
1 + 1 + 1 + returned value of 4th call =... and so on.
Finally as result you'll get number of calls which is what you want.

Categories