9.1.6 Checkerboard V1 Codehs _verified_

The Goal

The objective is to create a checkerboard pattern using a 2D array logic concept. You are usually provided with a Rectangle class and a Checkerboard class (which uses Grid).

In "Checkerboard v1", the standard logic is to determine the color of a square based on the sum of its row and column indices.

8. Conclusion

The Checkerboard v1 problem teaches:

The solution demonstrates how to create an alternating pattern without knowing the grid size in advance, an essential concept in robotics and grid-based programming. 9.1.6 checkerboard v1 codehs

Variations and extensions

Detailed Explanation

  1. Nested Loops:

    • for(int row = 0; row < size; row++): This loop runs for every row.
    • for(int col = 0; col < size; col++): Inside every row, this loop runs for every column. This allows us to access every single cell in the grid.
  2. The Modulo Operator (%):

    • The core logic is (row + col) % 2 == 0.
    • The % operator returns the remainder of division.
    • If you divide a number by 2 and the remainder is 0, the number is even. If it is 1, the number is odd.
  3. Setting the Color:

    • We check if the coordinate sum is even. If it is, we set the rectangle color to Color.BLACK.
    • Otherwise (else), we set it to Color.WHITE.
  4. Grid Integration:

    • grid.add(rect, row, col);: This line is crucial. It places the colored rectangle we just created onto the visual Grid window at the specific coordinates so the user can see the checkerboard pattern.

Key Requirements:

3. Challenges

The Solution Code

In this specific CodeHS exercise, you typically edit the file named Checkerboard.java. You are expected to fill in the logic inside the nested for loops to set the color of the Rectangle objects stored in a 2D array.

Here is the completed code for the relevant section: The Goal The objective is to create a

/* 
 * This class represents a checkerboard. 
 * It creates a grid of Rectangle objects.
 */
public class Checkerboard
private Rectangle[][] board;
    private int size;
public Checkerboard(int size)
this.size = size;
    board = new Rectangle[size][size];
// Create the Grid to display the board
    Grid grid = new Grid(size, size, 50);
// Nested loops to iterate through the 2D array
    for(int row = 0; row < size; row++)
for(int col = 0; col < size; col++)
// 1. Create a new Rectangle object
            Rectangle rect = new Rectangle();
// 2. Determine color based on row + col sum
            if((row + col) % 2 == 0)
rect.setColor(Color.BLACK);
else
rect.setColor(Color.WHITE);
// 3. Add the rectangle to the array
            board[row][col] = rect;
// 4. Add the rectangle to the Grid to visualize it
            grid.add(rect, row, col);