Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you best convert a recursive function to an iterative one?

Tags:

java

recursion

This question is based on a test I had in a compsci class. In particular, I'm struggling to convert this function:

public static void foo(int number)  {
    if (number > 0) {
        foo(number / 2);
        System.out.print(number % 2);
    }
}

I need to convert this function to be non-recursive, but I'm struggling with it because the System.out.print(number % 2) occurs after the recursive call.

like image 401
Chris Chevalier Avatar asked Oct 31 '14 19:10

Chris Chevalier


People also ask

How do you convert a recursive function to iterative?

Initialize the accumulator before the while-loop. Use the negation of the base-case condition as the loop's condition. Use the recursive function's body (except the recursive call) as the body of the while-loop. After the loop, apply the base-case update of the accumulator and return its value.

Can you convert recursive to iteration?

Every recursive function can be transformed into an iterative function by replacing recursive calls with iterative control constructs and simulating the call stack with a stack explicitly managed by the program.

What is used to convert recursive to iterative implementation of an algorithm?

Which data structure is best suited for converting recursive implementation to iterative implementation of an algorithm? Explanation: Since function calls are executed in Last In First Out order, stack is the data structure for converting recursive to iterative implementation.

How can I convert a recursive function to iteration?

All recursive functions can be converted to iteration by simulating the stack to store state. However, recursion is usually slower and uses more memory because of the overhead of creating and maintaining stack frames. This doesn't mean never use recursion though. Recursion is the better choi BS in CS and 12 years of work experience in programming.

How to calculate the first recursive call of a recursive function?

the first recursive call should have been cache [n] = 1 + countChain (n / 2, cache) instead of cache [n] = 1 + countChain (n, cache) Someone asked for example data so I will simply type in the whole code (not that long) for a better understanding.

How do recursive algorithms work?

Most recursive algorithms have iterative variants, which end up looking similar to our makeTree function – that is, they use a stack data structure rather than the program stack. Our goal is to come up with a step by step process that will work for any piece of code without having to think too hard.

How do you convert a recursive call to a tail call?

Convert all recursive calls into tail calls. (If you can’t, stop. Try another method.) Introduce a one-shot loop around the function body. Convert tail calls into continue statements. Tidy up. An important property of this method is that it’s incrementally correct – after every step you have a function that’s equivalent to the original.


1 Answers

You can always simulate the stack of course but in a lot of cases you can convert it to a completely stackless solution. (I'm not 100% sure but I think the stack-free conversion is only possible for primitive recursive functions. I can see no way something like the Ackermann function can be computed without some sort of stack.)

Anyway, for most cases in practice (and all cases in the class room) it is possible to find a way. Here we can use the counter trick:

public static void foo(int number)  {
    for ( int divisor = 1; divisor <= number; divisor *= 2) {
      System.out.print( (number / divisor) % 2 );
    }
}

Update: The easiest practical way to convert simple functions like this is to run it, write down the output after each iteration, then forget about recursion completely, forget about the original code, look at the output alone and ask yourself: what is this code doing? Then just try to write iterative code that produces the same output. This technique served me well at uni. It doesn't always work in real life though. :)

like image 52
biziclop Avatar answered Sep 23 '22 10:09

biziclop