I try to create a Nim game with max min method. Then this is the code i create to build tree. Why this list can only store the last element? Please help
list.add(array);
This is my class
class Node {
public static int jml = 0;
public List<int[]> list; //only one list is needed (to insure)
Node n; //not needed also (can be removed)
public void mulai(int[] arg, String tipe){
int sisa, index = 0, o = 0;
boolean cek=false;
int array[] = new int[arg.length+1];
list=new ArrayList<int[]>();
n=new Node();
int[] arrayCloned = null;
for(int nilai : arg)
{ //Looping untuk tiap nilai pada array
for(int i = 1; i<nilai/2+1;i++)
{ //Looping untuk pengurangan
sisa = nilai - i;
if(sisa!=i){
for(int n = 0; n<array.length ;n++)
{ //Looping untuk membuat turunan
try{
if(n == index){
array[n]=sisa;
array[n+1]=i;
n++;
cek=true;
}else{
if(cek)
array[n]=arg[n-1];
else
array[n]=arg[n];
}
}catch(ArrayIndexOutOfBoundsException e){
}
} //Akhir looping turunan
System.out.printf("i = %d\n",i);
System.out.println("Befor add");
printListOfArray();
list.add(array); /*This code can only store the last element*/
System.out.println("After add");
printListOfArray();
System.out.println("======================");
if(tipe.equals("min"))
n.mulai(array, "max");
else
n.mulai(array, "min");
}
} //Akrir looping pengurangan
index++;
} //Akhir looping nilai array
}
void printListOfArray(){
for(int[] ins:list){
System.out.print("Elements: ");
for(int i:ins)
System.out.print(" "+i);
System.out.println();
}
}
public void print(){
for(int[] nilai : n.list){
System.out.println(Arrays.toString(nilai));
}
}
}
I have trouble here
list.add(array);
Please Help. I dont know whats wrong with my code This is output i have
i = 1 Befor add After add Elements: 4 1
i = 1 Befor add After add Elements: 3 1 1
i = 1 Befor add After add Elements: 2 1 1 1
i = 2 Befor add Elements: 3 2
After add Elements: 3 2 Elements: 3 2
i = 1 Befor add After add Elements: 2 1 2
I dont know why this is keep change. i = 1 there save 4 1, when i = 2 it change to 3 2