I have an algorithm to count each permutation of an int array. In this case - when I want to print these permutations - everything worked fine. But if I want to save the arrays to the arraylist, it saved the correct number of them, but it saved only the one same option. I know that the problem will be trivial, but I can't solve it. Thanks for your help.
I add to the method printArray, that it saved the printed Array to Arraylist afterwards.
Output of printArray is correct, but output of printList is like this:
1 2 3 4 5 6
(and this input is printed n!, which is correct but its only one permutation)
Here is my code:
public class Permute {
ArrayList<int[]> list;
public Permute() {
list=new ArrayList<>();
}
void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
list.add(a);
}
void printList(){
for(int[] arr:list){
for(int item:arr){
System.out.print(item+" ");
}
System.out.println("");
}
}
void permute(int[] a, int k) {
if (k == a.length)
printArray(a);
else {
for (int i = k; i < a.length; i++) {
int temp = a[k];
a[k] = a[i];
a[i] = temp;
permute(a, k + 1);
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}
public static void main(String[] args) {
Permute p = new Permute();
int a[] = {1, 2, 3, 4, 5, 6};
p.permute(a, 0);
p.printList();
}
}
a) to the list. Later changes to that array are then reflected in all references. Add a copy ofato the list each time:list.add(Arrays.copyOf(a, a.length))