I wrote a method and when I added some insignificant code like this:
array[1]=array[1];
array[0]=array[0];
array[3]=array[3];
array[2]=array[2];
it worked faster!
I used double t = System.currentTimeMillis();
at first to record the time.
Then I called the method and used System.out.println(System.currentTimeMillis()-t);
at the end.
Without the code (array[1]=array[1];...
) the runing time was 1035.0 ms, but if with the code added, the running time became 898.0ms.
Here is my method and my code. PS:this method is used for the game 2048, exp: {2,2,2,2} trans to {0,0,4,4}
static void toRight2(int[] array){
if (array[2]==array[3] ) {
array[3]=array[2]*2;
if (array[0]==array[1]) {
array[2]=array[1]*2;
array[0]=0;
array[1]=0;
}else {
array[2]=array[1];
array[1]=array[0];
array[0]=0;
}
} else{
if (array[0]==array[1]) {
array[1]=array[1]*2;
array[0]=0;
array[3]=array[3];
array[2]=array[2];
}else {
array[1]=array[1];//delete this cost more time
array[0]=array[0];//delete this cost more time
array[3]=array[3];//delete this cost more time
array[2]=array[2];//delete this cost more time
}
}
}
public static void main(String[] args) {
double t=System.currentTimeMillis();
int[] array={1,2,3,3};
for (int j = 2; j <400*1000000; j++) {
toRight2(array);
}
System.out.println(System.currentTimeMillis()-t);
}