简体   繁体   中英

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

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;
    }
}

There are several problems with your approach:

  • You use char s when you should use int s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM