In the CodeHS exercise 9.1.6: Checkerboard v1, the goal is to create a 2D array representing an
checkerboard where squares alternate between two values (usually 0 and 1). Core Concept: The Modulo Pattern
The most efficient way to determine the color of a square at position (row, col) is to check if the sum of the row and column indices is even or odd. Even sum (row + col % 2 == 0): One color (e.g., 0). Odd sum (row + col % 2 != 0): The other color (e.g., 1). Implementation Steps
Initialize the Array: Create a 2D integer array with 8 rows and 8 columns.
Nested Loops: Use a for loop to iterate through each row, and a nested for loop to iterate through each col.
Apply Logic: Inside the loops, use an if-else statement or a simple calculation to assign the value based on the parity of the sum of the indices. 9.1.6 checkerboard v1 codehs
Print: Use a helper method or another nested loop to print the grid so it looks like a board. Sample Code Structure (Java)
int[][] board = new int[8][8]; for (int row = 0; row < 8; row++) for (int col = 0; col < 8; col++) if ((row + col) % 2 == 0) board[row][col] = 0; else board[row][col] = 1; Use code with caution. Copied to clipboard Common Pitfalls
Off-by-one errors: Ensure your loops run from 0 to 7 (less than 8).
Index order: Always use board[row][col] to stay consistent with standard grid notation.
A checkerboard alternates colors. If you look at the coordinates (row, col): In the CodeHS exercise 9
(row + column) is even, the square is usually Black.(row + column) is odd, the square is usually White.Example:
Here is the Java code for CodeHS 9.1.6 Checkerboard v1:
import acm.graphics.*; import acm.program.*; import java.awt.*;public class CheckerboardV1 extends GraphicsProgram
// Define constants for better readability private static final int ROWS = 8; private static final int COLUMNS = 8; private static final int SQUARE_SIZE = 50; private static final int WINDOW_WIDTH = COLUMNS * SQUARE_SIZE; // 400 private static final int WINDOW_HEIGHT = ROWS * SQUARE_SIZE; // 400 public void run() // Set the canvas size setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Loop through each row for (int row = 0; row < ROWS; row++) // Loop through each column in the current row for (int col = 0; col < COLUMNS; col++) // Calculate the top-left corner of the square int x = col * SQUARE_SIZE; int y = row * SQUARE_SIZE; // Create the square (rectangle) GRect square = new GRect(x, y, SQUARE_SIZE, SQUARE_SIZE); // Determine the color based on parity if ((row + col) % 2 == 0) square.setFillColor(Color.GRAY); else square.setFillColor(Color.BLACK); // Make sure the square is filled with the color square.setFilled(true); // Add the square to the canvas add(square);
Core observation: parity (even/odd) of row+column determines which symbol to place.
Algorithm (textual):
Proof of correctness:
Complexity analysis: