mohan babu
mohan babu

Reputation: 1448

Performing Recursion inside For loop

I am trying to understand the code of writing permutations for a given input string.

For Example: Input String:123,Output:123,132,213,231,312,321.

Below pasted code snippet does that.

 public static void main(String args[]) {

    permuteString("", "123");
   }

public static void permuteString(String beginningString, String endingString) {
    if (endingString.length() <= 1)
        System.out.println(beginningString + endingString);
    else
        for (int i = 0; i < endingString.length(); i++) {
            try {
                 // System.out.println(i);
                String newString = endingString.substring(0, i) + endingString.substring(i + 1);
                permuteString(beginningString + endingString.charAt(i), newString);
            } catch (StringIndexOutOfBoundsException exception) {
                exception.printStackTrace();
            }
        }

I am getting very confused about when integer 'i' gets incremented in the for loop i.e from i=0 to 1. one thing i understood from the first iteration is 'i' got incremented to 1 when it hit the base case i.e

   if (endingString.length() <= 1)
        System.out.println(beginningString + endingString);

I tried to debug further , i value kept on changing between 0 and 1 for successive iterations which i couldn't understand.

To Sum-up, I am confused regarding the relationship between "for loop" and the two instructions in the try block after the first iteration.

I would be happy if some one can guide me through the process.

Upvotes: 5

Views: 2109

Answers (2)

karim mohsen
karim mohsen

Reputation: 2254

I tried to elaborate as much as i can with a drawing i hope it is helpful. This recursion doesn't need a try-catch block, you can remove it and it will work just fine

enter image description here

Upvotes: 3

gabowsky
gabowsky

Reputation: 652

It's not that complex: the permuteString function goes through all the characters of endingString, and adds it to the end of the so-far-constructed beginning string. (And removes that character from the endingString) In the next permuteString call it continues the work with a larger beginningString and shorter endingString.

This recursion doesn't really need a try-catch block, you can remove the catch and it'll be fully functionable.

Upvotes: 1

Related Questions