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:
char
s when you should use int
s and vice versa;System.out.print
statements, so you never instruct the Java program to print anything;for
part and keep building up a call stack; andp
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;
}
}
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.