Actually you should break the function down first:
A loop has a few parts:
the header, and processing before the loop. May declare some new variables
the condition, when to stop the loop.
the actual loop body. It changes some of the header's variables and/or the parameters passed in.
the tail; what happens after the loop and return result.
Or to write it out:
foo_iterative(params){
header
while(condition){
loop_body
}
return tail
}
Using these blocks to make a recursive call is pretty straightforward:
foo_recursive(params){
header
return foo_recursion(params, header_vars)
}
foo_recursion(params, header_vars){
if(!condition){
return tail
}
loop_body
return foo_recursion(params, modified_header_vars)
}
Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.
Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.
We can use a switch to work around that:
bar_recurse(params){
if(baseCase){
finalize
return
}
body1
bar_recurse(mod_params)
body2
bar_recurse(mod_params)
body3
}
bar_iterative(params){
stack.push({init, params})
while(!stack.empty){
stackFrame = stack.pop()
switch(stackFrame.resumPoint){
case init:
if(baseCase){
finalize
break;
}
body1
stack.push({resum1, params, variables})
stack.push({init, modified_params})
break;
case resum1:
body2
stack.push({resum2, params, variables})
stack.push({init, modified_params})
break;
case resum2:
body3
break;
}
}
}
Answer from ratchet freak on Stack ExchangeActually you should break the function down first:
A loop has a few parts:
the header, and processing before the loop. May declare some new variables
the condition, when to stop the loop.
the actual loop body. It changes some of the header's variables and/or the parameters passed in.
the tail; what happens after the loop and return result.
Or to write it out:
foo_iterative(params){
header
while(condition){
loop_body
}
return tail
}
Using these blocks to make a recursive call is pretty straightforward:
foo_recursive(params){
header
return foo_recursion(params, header_vars)
}
foo_recursion(params, header_vars){
if(!condition){
return tail
}
loop_body
return foo_recursion(params, modified_header_vars)
}
Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.
Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.
We can use a switch to work around that:
bar_recurse(params){
if(baseCase){
finalize
return
}
body1
bar_recurse(mod_params)
body2
bar_recurse(mod_params)
body3
}
bar_iterative(params){
stack.push({init, params})
while(!stack.empty){
stackFrame = stack.pop()
switch(stackFrame.resumPoint){
case init:
if(baseCase){
finalize
break;
}
body1
stack.push({resum1, params, variables})
stack.push({init, modified_params})
break;
case resum1:
body2
stack.push({resum2, params, variables})
stack.push({init, modified_params})
break;
case resum2:
body3
break;
}
}
}
Following up on @ratchet freak's answer, I created this example of how the Fibonacci function can be rewritten to a while loop in Java. Note that There's a much simpler (and efficient) way to rewrite the Fibonacci with a while loop though.
class CallContext { //this class is similar to the stack frame
Object[] args;
List<Object> vars = new LinkedList<>();
int resumePoint = 0;
public CallContext(Object[] args) {
this.args = args;
}
}
static int fibonacci(int fibNumber) {
Deque<CallContext> callStack = new LinkedList<>();
callStack.add(new CallContext(new Object[]{fibNumber}));
Object lastReturn = null; //value of last object returned (when stack frame was dropped)
while (!callStack.isEmpty()) {
CallContext callContext = callStack.peekLast();
Object[] args = callContext.args;
//actual logic starts here
int arg = (int) args[0];
if (arg == 0 || arg == 1) {
lastReturn = arg;
callStack.removeLast();
} else {
switch (callContext.resumePoint) {
case 0: //calculate fib(n-1)
callStack.add(new CallContext(new Object[]{arg - 1}));
callContext.resumePoint++;
break;
case 1: //calculate fib(n-2)
callContext.vars.add(lastReturn); //fib1
callStack.add(new CallContext(new Object[]{arg - 2}));
callContext.resumePoint++;
break;
case 2: // fib(n-1) + fib(n-2)
callContext.vars.add(lastReturn); //fib2
lastReturn = (int) callContext.vars.get(0) + (int) callContext.vars.get(1);
callStack.removeLast();
break;
}
}
}
return (int) lastReturn;
}
Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.
Like this:
Object loop(int i, Object data) {
if (i > 0) {
return loop(i - 1, evolve(data));
} else {
return data;
}
}
That's the same as this:
for ( ; i > 0; i--) {
data = evolve(data);
}
In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.
In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.
Haters aside, let's do this! [1]
Given:
int x = 3;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++){
list.add(array[i] + array[j] + array[k]);
}
}
}
Let's consider that each loop is it's own recursive function - as this makes the recurrence cases much easier! This is also the only "non-thinking" method I know of to turn the loops into recursion. The recursive depth will be limited to 3*x => i+j+k so it's "fairly safe" for a smallish[2] x.
In Java it requires a separate method for each loop to encode this structure. (In a language with higher-order functions these three functions might be abstractly combined .. but not in Java [7].)
void loopI(int i) {
if (i < x) {
loopJ(0); // "start j loop"
loopI(i++); // "next i loop" / recurrence case
}
// "end loop" / base case
}
void loopJ(int j) {
if (j < x) {
loopK(0);
loopJ(j++);
}
}
void loopK(int k) {
if (k < x) {
list.add(array[i] + array[j] + array[k]);
loopK(k++);
}
}
// do it!
loopI(0);
All of these could be combined into a single recursive function, but that makes handling the recurrence cases a bit tougher as "thinking" and additional conditionals (or mod expressions, perhaps) are required to advance the state.
Here is an example of a combined recursive function (this is incorrect when x is 0). Unlike the three method approach above, the stack depth will grow to x^3 => i*j*k. This will easily kill Java's recursion limits - even for smallish values of x- as Java [7] doesn't have tail-call optimization.
void loop(int i, int j, int k) {
list.add(array[i] + array[j] + array[k]);
// advance states
k++;
if (k == x) { k = 0; j++; }
if (j == x) { j = 0; i++; }
if (i == x) { i = 0; }
// terminate on all wrap-around
if (i == 0 && j == 0 && k == 0) { return; }
// recurse
loop(i, j, k);
}
[1] YMMV, for theoretical purposes only - I love recursion, but it's not suited for this case in Java.
[2] For some value of "smallish". See how deep your stack can go!
Transfer for loop to recursion, Java - Stack Overflow
java - For loop to Recursion - Stack Overflow
java - converting while loop to recursion - Stack Overflow
java - Convert Recursion to Loop or another faster solution - Stack Overflow
Videos
can Someone help me convert this iterative function into a recursive function?
public int getMax(int [] A, int i, int j){
int max = A[i];
for (int k = i+1; k <=j ; k++) {
if(A[k]>max){
max = A[k];
}
}
return max;
}
I do not really understand recursion. I know the function will call itself at some point, but i'm pretty confused still.
This looks like a simple recursion:
public int GPA(double[] gpas, int index){
if(index >= gpas.length) return 0;
if(0 < gpas[index] && gpas[index] < 2) return 1 + GPA(gpas, index + 1);
else return GPA(gpas, index + 1);
}
Just call it GPA(gpa, 1).
There is a lot of unnecessary comparisons in your method. Look at your uses of 10, L and start.
For example, suppose start = 0. No one of your ifs will enter. Better to start with 1. Look:
if (start > 0 && start != L) //start is 0 so this won't enter
else if (start == L) //start is 0 so this won't enter
else if (start < 0 && start > L) //start is 0 so this won't enter
There are three most important things about a recursive function/method:
- The terminating condition.
- The value with which the method/function is called recursively.
- Where (before/after the recursive call) to process the parameter(s).
Do it as follows:
public class Main {
public static void main(String[] args) {
double[] gpa = new double[] { 2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2 };
int start = 0;
System.out.println(countGPA(gpa, start));
}
public static int countGPA(double[] gpas, int start) {
return countGPA(gpas, start, 0);
}
public static int countGPA(double[] gpas, int start, int count) {
if (start >= gpas.length) {// Terminating condition
return count;
}
if (gpas[start] < 2.0 && gpas[start] > 0) {
return countGPA(gpas, ++start, ++count);// The recursive call
} else {
return countGPA(gpas, ++start, count);// The recursive call
}
}
}
Output:
4
Googling "how to convert for loop to recursion," there's a similar answer here, and an article with an example here.
This is a pretty big hint but the basic idea is that your arguments store the current loop state.
for (int i = 1; i <= n; i++)
{
// ....
}
is equivalent to:
private static void PerformAction(int n)
{
if (n > 0)
{
// Do something
PerformAction(n - 1);
}
}
This is something you should be able to Google pretty easily, make sure you try finding the answer yourself before asking the community. I don't mind answering questions like this, but I've found that you don't really learn anything if you ask first and look later.
private static void printStars(int n)
{
if (n>0){
system.out.println("*");
printStars(n-1);
}
}
So this is not pretty, but it works without recursion. Also i changed the return type from double to int because of reasons:
public static int sum(int z, int x, int y)
{
// Compute number of calls
int[][] calls = new int[x+1][x*y+1];
calls[0][0] = 1;
for (int i = 0; i < x; i++) {
for (int j = 0; j <= x*y; j++) {
for (int target = j+1; target <= j+y && target <= x*y; target++) {
calls[i+1][target] += calls[i][j];
}
}
}
// Return count of last column where z <= 0
int result = 0;
for (int j = x*y; z-j <= 0; j--) {
result += calls[x][j];
}
return result;
}
To understand, have a look at this high-tech Excel sheet:

This chart illustrates a call of sum(3, 3, 3). Horizontally you see x and vertically you see z both get smaller. y is 3 and not changed.
The top left 1 means one call to sum(3, 3, 3). This call then spawns three child calls (because of y=3): sum(2, 2, 3), sum(1, 2, 3) and sum(0, 2, 3). These three calls are found in the next column (where x=2).
Each of those three calls then spawns again three calls, shown in the row of x=1. These nine calls overlap a bit regarding z. Each of those nine calls then spawns again three calls, resulting in 27 calls in the x=0 column.
To get the result, you simply count all calls in the x=0 column, where z <= 0. In this example this is every call, so you get a result of 27. For a larger z the result would be smaller.
public static double sum(int z, int x, int y) {
int num = 0;
for (int i = 0; i <= y; i++) {
if (z - x - i > 0) {
num++;
}
}
return (double) (Math.pow(y, x) - num);
}
Explanation: your method launches at most y^x recursive calls. On the last level of recursion, where x == 0, you have to determine the max value of z throughout all the calls and check how many of these calls do have z > 0, so that the call returns 0 and you do not have to take it into account. Now, on the last level of recursion, the max value of z is given by z - x. You now simply count all the instances in the for loop for which z - x stays positive so it does not influence your sum. After you computed that number, substract it from the initial approximation of the result, which was y^x.
Like so:
public class Recursive {
public void r(int i) {
if (i < 1024) {
i *= 2;
System.out.println("Count is: " + i);
r(i);
}
}
public static void main(String[] args) {
Recursive r = new Recursive();
r.r(1);
}
}
Take the loop of main and put it in its own function with an argument int i. In that function, rewrite the loop to
- If the loop condition is false (
i >= 1024), thenreturn - Else, recursive call with argument
i*2.
Call the function with argument 1 or 2, depending on which of your programs you're rewriting (they don't entirely match).
BASIC PROBLEM
They don't "go back to their old state" -- those variables are destroyed (released back to the memory heap) when you exit the method instance.
Those are local variables -- allocated when you enter the method, released on exit; some are input parameters, and receive their initial values from the arguments to the call. Thus, they don't "go back to their old state". What you're seeing is the unchanged states from the previous instance of the method.
Each time you call the routine, you add another instance to the stack. Each instance has its own version of the variables, which happen to share names. They do not share values.
SOLUTION
You work around this by keeping to basic principles of modular programming: you pass values into a method with the parameter list; you get values back with the return list. For instance, your final else clause might look something like this:
child_result = recurs(j1, index1, index2, indexTab1,
tab1, tab2, tab3, nZeros,
cost, i, tab1Index, b);
tools.add(child_result);
return tools;
I have not read your code for functionality; you may well need something other than tools.add(child_result) to accumulate the proper values. However, I believe that I've given you the basic principle that's currently giving you trouble.
The problem was coming from pointers, the variables i used as parameters only stayed changed for the method and came back to their old state when it ended. I bypassed this by setting the variable as static class variables, and resetting them when i wanted to, but the solution from Prune looks better and less messy.
If you don't want to change the contract you do it by making a helper.
private static void permutationFor(int i, int n, String prefix, String str) {
if( i < n ) {
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i+1, n));
permutationFor(i+1, n, prefix, str);
}
}
Thus you change the for loop with a call to permututaionFor
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
System.out.println(prefix);
} else {
premutationFor(0, n, prefix, str);
}
}
Add parameters to represent the lower and upper bounds,
private static void permutation(String prefix, String str, int i, int j) {
add a boundary condition at the beginning of permutation,
if(i < j){
then omit the for loop, and in your already-recursive call to permutation,
permutation(..., i+1, j);
and finally, when you call it initially from your other code, pass 0 and the parameter str's .length() as the values of i and j.
You could also create another permutation(...) overload that takes the two extra parameters, so your initial call doesn't have to figure them out.
Note that you can remove some of the redundancy around n in your code, but you can get this working without doing so.