9.1.7 Checkerboard V2: Codehs
public class CheckerboardV2 extends ConsoleProgram public void run() // Define the dimensions of the checkerboard int rows = 8; int cols = 8; // Initialize the 2D array int[][] board = new int[rows][cols]; // Populate the array using nested loops for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) // Check if the sum of indices is even if ((r + c) % 2 == 0) board[r][c] = 1; // Primary value else board[r][c] = 0; // Secondary value // Print the final grid to the console printBoard(board); private void printBoard(int[][] grid) for (int r = 0; r < grid.length; r++) for (int c = 0; c < grid[r].length; c++) System.out.print(grid[r][c] + " "); System.out.println(); // Move to the next line after each row Use code with caution. Common Pitfalls and Troubleshooting
Your goal is to build the my_grid list that holds the checkerboard data. To do this efficiently, you'll use a list comprehension, which is a concise way to create a list by applying an expression to each item in an existing sequence. Here's how to break it down:
: (row + col) % 2 == 0 checks if the sum is even → one color; odd → other color.
You can see a pattern: whenever the sum of the row index i and column index j is , a 1 should be placed. If the sum is even , a 0 should be placed 1.2.4. Solving 9.1.7 Checkerboard V2 in Python 9.1.7 Checkerboard V2 Codehs
Depending on the exact problem, you might need to create the grid or it might be passed to you. If you need to build it, you can do so using list multiplication for efficiency:
Happy coding! 🧩
Here is the most robust approach to solving this problem, focusing on creating the 2D array and then populating it. You can see a pattern: whenever the sum
Use the graphics function to draw the rectangle at with the determined color. Example Solution Snippet
:
Adding to Screen: Don't forget to use the add() function inside the inner loop so every individual square is rendered to the canvas. If you need to build it, you can
0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0
def build_fancy_checkerboard(rows, cols, char_a='X', char_b='O'): board = [] for i in range(rows): row = [] for j in range(cols): if (i + j) % 2 == 0: row.append(char_a) else: row.append(char_b) board.append(row) return board
When you run the code, you should see: