MCPcopy Create free account
hub / github.com/careercup/ctci / Board

Class Board

java/Chapter 8/Question8_8/Board.java:3–138  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package Question8_8;
2
3public class Board {
4 private int blackCount = 0;
5 private int whiteCount = 0;
6 private Piece[][] board;
7
8 public Board(int rows, int columns) {
9 board = new Piece[rows][columns];
10 }
11
12 public void initialize() {
13 /* initial board has a grid like the following in the center:
14 * WB
15 * BW
16 */
17 int middleRow = board.length / 2;
18 int middleColumn = board[middleRow].length / 2;
19 board[middleRow][middleColumn] = new Piece(Color.White);
20 board[middleRow + 1][middleColumn] = new Piece(Color.Black);
21 board[middleRow + 1][middleColumn + 1] = new Piece(Color.White);
22 board[middleRow][middleColumn + 1] = new Piece(Color.Black);
23 blackCount = 2;
24 whiteCount = 2;
25 }
26
27 public boolean placeColor(int row, int column, Color color) {
28 if (board[row][column] != null) {
29 return false;
30 }
31
32 /* attempt to flip each of the four directions */
33 int[] results = new int[4];
34 results[0] = flipSection(row - 1, column, color, Direction.up);
35 results[1] = flipSection(row + 1, column, color, Direction.down);
36 results[2] = flipSection(row, column + 1, color, Direction.right);
37 results[3] = flipSection(row, column - 1, color, Direction.left);
38
39 /* compute how many pieces were flipped */
40 int flipped = 0;
41 for (int result : results) {
42 if (result > 0) {
43 flipped += result;
44 }
45 }
46
47 /* if nothing was flipped, then it's an invalid move */
48 if (flipped < 0) {
49 return false;
50 }
51
52 /* flip the piece, and update the score */
53 board[row][column] = new Piece(color);
54 updateScore(color, flipped + 1);
55 return true;
56 }
57
58 private int flipSection(int row, int column, Color color, Direction d) {
59 /* Compute the delta for the row and the column. At all times, only the row or the column
60 * will have a delta, since we're only moving in one direction at a time.

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected