0. Here is a print2DArray method that will be useful for testing your work:
public static void print2DArray(String[][] arr) { System.out.print("[ "); for (int i = 0; i < arr.length; i++) { if (i != 0) System.out.print(" "); System.out.print("["); for (int j = 0; j < arr[0].length; j++) { System.out.print(arr[i][j]); if (j != arr[0].length - 1) { System.out.print(", "); } } System.out.print("]"); System.out.println(i == arr.length - 1 ? " ]" : ","); } }
Copy and paste print2DArray into Eclipse and overload the method so it also works on 2D arrays of ints.
1. Write a method alternatingBoard that takes a 2D array of Strings as its inputs and works like this:
Given:
String[][] strs = new String[4][7]; alternatingBoard(strs); print2DArray(strs);
then strs the output will be:
[ [ X, O, X, O, X, O, X ], [ O, X, O, X, O, X, O ], [ X, O, X, O, X, O, X ], [ O, X, O, X, O, X, O ] ]
2. Write the method neighbors that takes a 2D array of booleans as its input. It returns a 2D array of ints, where the int at position (row, col) in the array contains the number of neighbors of (row, col) that are true. A neighbor is defined to be a position that is adjacent either horizontally, vertically, or diagonally.
Examples:
boolean[][] grid = { { true, false, false}, { false, false, false }, { false, true, false } };
will print:
[ [0, 1, 0], [2, 2, 1], [1, 0, 1] ]
and
boolean[][] grid = { { false, false, false, false, false, true, false }, { false, false, true, false, false, false, false }, { false, true, false, true, false, false, false }, { false, false, true, false, false, false, true }, { false, false, false, false, true, false, false } }; print2DArray(neighbors(grid));
will print:
[ [0, 1, 1, 1, 1, 0, 1], [1, 2, 2, 2, 2, 1, 1], [1, 2, 4, 2, 1, 1, 1], [1, 2, 2, 3, 2, 2, 0], [0, 1, 1, 2, 0, 2, 1] ]