Skip to content

Instantly share code, notes, and snippets.

@Determinant
Last active August 9, 2016 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Determinant/034dcd66dd3dd232704f to your computer and use it in GitHub Desktop.
Save Determinant/034dcd66dd3dd232704f to your computer and use it in GitHub Desktop.
/*
* Author: Ted Yin (Maofan Yin) <ted.sybil@gmail.com>
* Description: Implementation for performing a move in direction left in 2048 game
*/
class Game2048 {
public int moveLeft(int[][] b, int i) {
int bonus = 0;
int h = 0; /* b[i][0..h-1] has its final value and cannot be changed
again (exactly the same definition in your hint) */
boolean moveMade = false;
/* loop invariant:
* +-------------row: b[i]----------------------+
* |###########<x>00000000??????????????????????|
* +0-----------h---------j---------------------+
* "#": has their final values and cannot be changed
* "<x>": the next value to be finalized (still mergable)
* "0": blanks
* "?": not discovered
*/
for (int j = 1; j < b[i].length; j++)
{
if (b[i][j] == 0) continue; /* skip blanks */
if (b[i][j] == b[i][h])
{
bonus += (b[i][h++] += b[i][j]); /* merge with the previous same value:
<x>, z, ..., x --> (x + x), <z>, ... */
moveMade = true;
b[i][j] = 0;
}
else
{
/* different value, so that the value x at h already has its final value */
if (b[i][h] == 0)
{
b[i][h] = b[i][j]; /* <0>, ..., y --> <y>, ... */
b[i][j] = 0;
}
else
{
b[i][++h] = b[i][j]; /* <x>, 0, ..., y --> x, <y>, ... */
if (h != j)
{
moveMade = true;
b[i][j] = 0;
}
/* if h == j, nothing is moved */
}
}
}
return moveMade ? bonus: -1;
}
public static void main(String [] args) {
/* A simple test of written routine */
Game2048 game = new Game2048();
int[][] grid = new int[][]{new int[] {2, 4, 4, 8, 0, 8, 8}};
System.out.printf("%d:", game.moveLeft(grid, 0));
for (int j = 0; j < grid[0].length; j++)
System.out.printf(" %d", grid[0][j]);
System.out.printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment