class Square
{
public Square(boolean isBlack, int num)
{ /* implementation not shown */ }
}
class Crossword
{
private Square[][] puzzle;
public Crossword(boolean[][] blackSquares)
{
puzzle = new Square[blackSquares.length][blackSquares[0].length];
int label = 1;
for (int r = 0; r < blackSquares.length; r++) {
for (int c = 0; c < blackSquares[0].length; c++) {
if (toBeLabeled(r, c, blackSquares)) {
puzzle[r][c] = new Square(false, label);
label++;
} else {
puzzle[r][c] = new Square(blackSquares[r][c], 0);
}
}
}
}
private boolean toBeLabeled(int r, int c, boolean[][] blackSquares)
{
return (!(blackSquares[r][c]) &&
(r == 0 || c == 0 || blackSquares[r - 1][c] ||
blackSquares[r][c - 1]));
}
}
public class Main {
/** Returns true if the square at row r, column c should be labeled
* with a positive number; false otherwise.
* The square at row r, column c is black if and only if
* blackSquares[r][c] is true.
* Precondition: r and c are valid indexes in blackSquares.
*/
private boolean toBeLabeled(int r, int c, boolean[][] blackSquares)
{
return (!(blackSquares[r][c]) &&
(r == 0 || c == 0 || blackSquares[r - 1][c] ||
blackSquares[r][c - 1]));
}
// Driver (do not modify)
public void driver() {
boolean[][] grid = {
{true, false, false},
{false, false, true},
{false, true, false}
};
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[0].length; c++) {
System.out.println(
"Square (" + r + "," + c + ") labeled? " +
toBeLabeled(r, c, grid)
);
}
}
}
public static void main(String[] args) {
Main tester = new Main();
tester.driver();
}
}
Main.main(null);
Square (0,0) labeled? false
Square (0,1) labeled? true
Square (0,2) labeled? true
Square (1,0) labeled? true
Square (1,1) labeled? false
Square (1,2) labeled? false
Square (2,0) labeled? true
Square (2,1) labeled? false
Square (2,2) labeled? true
Challenges
One significant struggle is managing the “off-by-one” errors that often occur when checking neighboring squares, as looking at r - 1 or c - 1 can easily cause the program to crash if the boundaries of the array aren’t handled correctly. Hard to keep track of the multiple, overlapping conditions required to determine if a square needs a label versus staying blank. Difficult to coordinate the separate tasks of identifying a valid square and incrementing a specific label counter only when conditions are met.
What I learned
- learn how to effectively navigate 2D arrays using nested loops to process grid-based data structures
- deeper understanding of how to translate complex, wordy rule sets into concise and logical boolean expressions
Code Runner
