Chander Shivdasani
Chander Shivdasani

Reputation: 10131

permute a string

Given the String, print all its permutations. To do that, i came up with the following program.

public static char[] swap(char[] input, int i, int j) {
        char temp;
        temp = input[i];
        input[i] = input[j];
        input[j] = temp;

        return input;

    }

    /**
     * 
     * @param args
     */

    public static void permuteStrings(char[] inputString, int start, int finish ) {
        //Base case: When there is only single element, print the string
        if(start == finish) 
            System.out.println(inputString);
        else {
            //Recursive case: Swap first element with all the elements and permute on the 
                           // rest of string.
            for(int i = start; i <= finish; i++) {
                inputString = swap(inputString, start, i);
                permuteStrings(inputString, i + 1, finish);
                inputString = swap(inputString,start, i); //restoring the original string
            }
        }
    }

But, for the given input ABC, all it prints are

ABC
BAC

I cant seem to figure out what the problem is

Upvotes: 2

Views: 1753

Answers (2)

Nikhil_10
Nikhil_10

Reputation: 133

Use recursion

public static void permutation(String str) 
{ 
permutation("", str); 
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) 
 System.out.println(prefix);
else 
{
    for (int i = 0; i < n; i++)
     permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}

Upvotes: 0

Chander Shivdasani
Chander Shivdasani

Reputation: 10131

Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString, i + 1, finish);.

The correct way was:

permuteStrings(inputString, start + 1, finish);

Upvotes: 1

Related Questions