I'm trying to write a program to print all possible combinations of 28 variables that can be either 1 or -1 using a somewhat roundabout method, but the program isn't working. Specifically, I'm using an arraylist to store the solutions, but the stored arrays seem to be changing without my telling them to. I also tried a multidimensional array with the same result. Any help would be appreciated.
Here's my code:
int[] vals = new int [28];
Arrays.fill(vals, 1);
ArrayList <int[]> solutions = new ArrayList<int[]> (756);
long c=0; //counter
int ns=0; //number of solutions found
while (ns<756){
c++;
for(int i=0;i<28;i++){
if (c%(i+1)==0){
vals[i]*=-1;
}
}
boolean unique = true;
for(int i=0;i<ns;i++){
if(Arrays.equals(vals, solutions.get(i)) ){
unique = false;
}
}
if(unique==true){
solutions.add(vals);
ns++;
}
}
for(int i=0;i<756;i++){
System.out.println( "Solution "+ i);
for(int j=0;j<28;j++){
System.out.println("1: " + solutions.get(i)[j]);
}
System.out.println();
}
valsis an object reference. Every time you saysolutions.add(vals), you are adding a reference to that same array to theArrayList; you are not making a copy of the array. Look at theArrays.copyOfmethods.if(unique==true); instead useif(unique).