I'm new to Java (1month). I've been trying to do the below unsuccessfully, any help would be appreciated. What I'm trying to have is:
Main passes int array to method perm2.
perm2(new int[]{1,2,3});
perm2 will make permutations of it and add to an ArrayList and return it.
This is what I have so far. As you can see it just prints out the permutations.
Problem is I can't add them to an ArrayList and return.
public static void perm2(int[] s) {
int N = s.length;
int[] a = new int[N];
for (int i = 0; i < N; i++) a[i] = s[i];
perm2(a, N);
}
private static void perm2(int[] a, int n) {
if (n == 1) {
System.out.println(Arrays.toString(a));
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
private static void swap(int[] a, int i, int j) {
int c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
Output:
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
[1, 3, 2]
[2, 1, 3]
[1, 2, 3]
I don't really want to output them with sysout
. I just want them returned in ArrayList of int arrays.