I am trying to write a code that generates a List containing all the possible permutations of a given int array.
I have found online a method ("nextPermutation" in the code below) that allows to do that, and I am trying to implement it into a basic code, but it does not work.
The problem is that when I try to dynamically add the array containing the new permutation to the list, all the previous permutations already stored in the list are replaced with the new one.
I guess the problem is somehow related with the fact that my "nextPermutation" is non-static, but I have no idea about what I should do to fix it.
Any suggestion?
package lang_dist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class lang_dist {
public;
}
public static void main( String[] args )
{
int[] array = {0, 0, 1, 1, 1, 1};
List<int[]> rowList = new ArrayList<int[]>();
List<int[]> results = new ArrayList<int[]>();
lang_dist d=new lang_dist();
while (d.nextPermutation(array)){
System.out.println("Permutation:" + Arrays.toString(array));
results = Arrays.asList(array);
rowList.add(results.get(0));
};
System.out.println("---");
for (int[] row : rowList) {
System.out.println("Row = " + Arrays.toString(row));
}
}
}
The (main) problem is that you store your results in the same array at every permutation. Therefore,
rowList contains n references to the same array.
To (quickly) fix the problem, you need to create a new array for every permutation:
results = Arrays.asList(array.clone());
Besides,
results here is redundant, use
rowList or
results to store your permutations.
I suggest you have a look at: Are arrays passed by value or passed by reference in Java? Is Java "pass-by-reference" or "pass-by-value"?