1

Generating all permutations of a given string shows a recusive algorithm for finding all permutations of a string. Now I had a slightly different approach to the recusion (or maybe it's the same but I am not sure..) and I am having some trouble implementing it.

The algorithm goes as follows: The first element of a string will change position one index at a time until it reaches the end of the string. While it does that, the rest of the string will go thorugh permutation and will be added to the moving(first) element while keeping that (moving) element's current index fixed. So far this is what I have.

public static String permu(String s)
{
    return permu(s,"",0,s.length());
}
public static String permu(String s, String fixed, int fixi, int fullLength)
{
    String str = "";
    if(s.length() == 1)
    {
        if(fixi == 0) return fixed+s;
        else if(fixi == 1) return s+fixed;
    }
    else if(s.length() > 1)
    {
        String actual = "";
        for(int i = 0; i < s.length(); i++)
        {
            actual = permu(s.substring(i,s.length()), s.substring(0,1),i,fullLength); // permu function will always return 
            if(actual.length() == fullLength) // the last two element .. I think
                System.out.println(actual);
        }
        return actual; // don't think this is needed
    }
    return str; // same for this.
}

Examples:

 ------------ permutation of 1234  -----------------------
 234
 1 (permutation of 234 but 1 has to be at index 0)

 ...................
 234    
    1 (permutation of 234 but 1 has to be at index 1)

 ...................
 234    
        1 (permutation of 234 but 1 has to be at index 2)

 ...................
 234
            1 (permutation of 234 but 1 has to be at index 3)


 ------------ permutation of 234  -----------------------
 34
 2 (permutation of 34 but 2 has to be at index 0)

 ...................
 34
    2 (permutation of 34 but 2 has to be at index 1)

 ...................
 34 
        2 (permutation of 34 but 2 has to be at index 2)

 ------------ permutation of 34  -----------------------
 4
 3 (permutation of 4 but 3 has to be at index 0)

 ...................
 4
    3 (permutation of 4 but 3 has to be at index 1)

 */

/*
 1234

 1  234
    243
    423
    324
    342
    432


 2  1 34
 2    43
 3    24
 4    23
 3    42
 4    32


 23 1 4
 24   3
 32   4
 42   3
 34   2
 43   2

234   1
243
423
324
342
432

 */
Community
  • 1
  • 1

0 Answers0