0
votes

I have written a recursive method using nested loops to print all permutations of a given string.It prints all the permutations but more than once can someone figure out the problem and what to change in conditions to solve this?

public static String swap(String x,int a,int b){
    char list[]=x.toCharArray();
    char tmp=x.charAt(a);
    list[a]=list[b];
    list[b]=tmp;
    return new String(list);
}
public static void perm(String x,String base){
    if(base.length()==3)
        System.out.println(base);
    for(int i=0;i<x.length();i++)
        for(int j=i;j<x.length();j++){
            String tmp=swap(x,i,j);
            perm(tmp.substring(1),base+tmp.charAt(0));
        }
}

Example: Input :"abc". Output: abc acb abc bac bca bac cba cab cba abc acb abc acb abc acb abc acb abc.

1
Could you include input, expected output, and actual output.bhspencer
@bhspencer added thatAhmed Sami
where's the rest of the code for the perm method?Michael Markidis
@MichaelMarkidis It is all the codeAhmed Sami

1 Answers

0
votes

Below is the modified version I did based on your code.

public static void main(String[] args) {
    String str = "abc";
    char[] chars = str.toCharArray();
    perm(chars, 0);
}

public static void swap(char[] x, int a, int b) {
    char tmp = x[a];
    x[a] = x[b];
    x[b] = tmp;
}

public static void perm(char[] x, int idx) {
    if (idx == x.length) {
        for (int i = 0; i < x.length; i++)
            System.out.print(x[i]);
        System.out.println();
    }

    for (int i = idx; i < x.length; i++) {
        swap(x, idx, i);
        perm(x, idx + 1);
        swap(x, idx, i);
    }
}