Last active
August 9, 2016 01:32
Revisions
-
Ted Yin revised this gist
Jul 27, 2015 . 1 changed file with 13 additions and 9 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -30,18 +30,22 @@ public int moveLeft(int[][] b, int i) { } 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; -
Ted Yin created this gist
Jul 27, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,59 @@ /* * Author: Ted Yin (Maofan Yin) <[email protected]> * 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 { b[i][h += (b[i][h] != 0 ? 1 : 0)] = b[i][j]; /* different value, so that the value x at h already has its final value: if x == 0 <0>, ..., y --> <y>, ... else <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"); } }