Why can't I get any output from my recursive method?

60 views Asked by At

I'm trying to insert the characters (a, b, c) and get the permutation of the array.

For some reason its not printing out. I'm sure its a simple mistake but I can't find it. Much appreciative for the advice.

public static void main(String[] args) {

    int [] A = new int []{'a','b','c'};
    permute(A, 3);
}

public static void permute(int[] A, int p){
    if(A.length == 0){
        return;
    }
    for(int i = 0; i < A.length; i++){
        char ch = (char) p;
        p += A[i];
        permute(A,p);
        p = ch;
    }
}
1

There are 1 answers

1
willeM_ Van Onsem On

There are several problems with your approach:

  • You use chars when you should use ints and vice versa;
  • The program doesn't contain any System.out.print statements, so you never instruct the Java program to print anything;
  • This isn't a program that enumerates over all possible permutations. This will in fact generate a stack overflow exception (not to be confused with the name of this site), simply because the length of the array never changes, thus you always will call the for part and keep building up a call stack; and
  • It is unclear what p means.

An in-line permutation program looks like:

public static void permute(char[] a, int p){
    if(p >= a.length) {//we've reached the end of the array, now print
        for(int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
        }
        System.out.println();
    } else {
        char cp = a[p];
        for(int i = p; i < a.length; i++){
            char ci = a[i];
            a[p] = ci;
            a[i] = cp;
            permute(a,p+1);
            a[i] = ci;
        }
        a[p] = cp;
    }
}

online jDoodle.

Then you call the method with permute(a,0) with a the list of characters you wish to permutate.