java - How do I shift the contents of an array a la Super 2048? -
more specifically, how shift contents of array this:
[2 0 2 8]
into this:
[0 0 4 8]
edit: shifting, mean game of super 2048. think of array 1 row in 4x4 game. when enter command 'shift right', left number number equal it, element 0 being equal element 2. number in element 0 become 0 , 1 in element 2 add 4. if number fails find equal number, stops left of different number.
i tried manipulating array's elements directly code below, had no success.
for(int col = dimension-2; col >= 0; col--) { for(int tgtcol = col+1; tgtcol < dimension; tgtcol++) { if(initialstate[tgtcol] == initialstate[col]) { initialstate[tgtcol] += initialstate[col]; initialstate[col] = 0; } /*if(initialstate[tgtcol] == 0 && initialstate[col] != 0) { initialstate[tgtcol] = initialstate[col]; initialstate[col] = 0; } code later implementation */ else {} } }
this'll work you,
int[] targetstate = new int[dimension]; int tcol = dimension - 1; (int = dimension - 1; >= 0; i--) { if (initialstate[i] == 0) { continue; } else { if ((targetstate[tcol] == initialstate[i])) { targetstate[tcol] += initialstate[i]; tcol--; } else if (targetstate[tcol] == 0){ targetstate[tcol] = initialstate[i]; } else { targetstate[--tcol] = initialstate[i]; } } } initialstate = targetstate;
i think inplace shifting computationally expensive aproach.
Comments
Post a Comment