0

I noted down this code, to find the permutations of the entered String, in class today.

However, I don't seem to understand what's going on in the for loop in the , doPermute function especially after the part where it calls itself. How does it manage to execute the code written after it calls itself?! Would greatly appreciate some explanation.

P.S I know that this question might seem a bit amateur, I apologize for that as I haven't fully understood recursive functions as of yet.

Code :

import java.util.Scanner;
public class Permutation {



    public static void main (String args[])
   {
    System.out.println(" Enter the string to show permutations ");
    Scanner in = new Scanner(System.in);
    String original=in.nextLine();
    System.out.println("");
    System.out.println("");
    System.out.println("");
    System.out.println("Results are :");
    System.out.println("");
    System.out.println("");
    permute(original);
}



public static   void permute( String input)
{
    int inputLength = input.length();
    boolean used [] = new boolean[ inputLength ];
    StringBuffer outputString = new StringBuffer();
    char in[] = input.toCharArray( );
    doPermute ( in, outputString, used, inputLength, 0 );
}


public static    void doPermute ( char in[], StringBuffer outputString,
boolean used[], int inputLength, int level)
{

    if( level == inputLength) {
        System.out.println ( outputString.toString());
        return;
    }

    for( int i = 0; i < inputLength; i++ )
    {

        if( used[i] ) continue;

        outputString.append( in[i] );
        used[i] = true;
        doPermute( in,   outputString, used, inputLength, level + 1 );
        used[i] = false;
        outputString.setLength(   outputString.length() - 1 );
    }
 }

 }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Nikhil Gopal
  • 107
  • 3
  • 6
  • 11
  • Try with your debuger to follow the whole execution of your code on a simple 2 or 3 letter word... That may englighten you more than a thousand words. – GPI Mar 09 '15 at 16:03
  • Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "[Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts). BTW, it's "Thanks in advance", not "Thanks in advanced". – John Saunders Mar 18 '15 at 23:18

0 Answers0