Constructing a square matrix involves making a 2D array with the same number of rows and columns. A checkerboard pattern in the square matrix is created by filling the elements with alternating 1’s and 0’s such that adjacent elements have different values. In this thread, we will discuss that how we can create square matrix and make a checkboard pattern in it. Let understand how exactly, this matrix looks like below:
[[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]]
1. Using nested "for" loops:To create a square matrix with a checkerboard pattern, nested for loops can be used. This involves creating a square matrix using the `zero()` function from NumPy and then applying a for loop to fill the matrix with alternating 1's and 0's in a checkerboard pattern.
Here’s an example given below:
Note: The (i + j) % 2 == 0 condition checks whether the row number i plus the column number j is even or odd, and sets the value of the element to 1 if it’s even (to create the black squares in the checkerboard pattern).
2. Mask bitwise "XOR" implementation:
To create square matrix and fill it with checkerboard pattern, we can use
XOR implementation as shown below:
After creating array and finding indices, It applies a mask using bitwise
XOR to checks whether the sum of the row and column indices is
odd using modulo arithmetic, and sets the corresponding elements in the mask to 1. Finally, it sets the elements in the matrix where the mask is 1 to 1.
3. Using "list" comprehension:
Another way to create an 8x8 matrix and fill it with a checkerboard pattern is by using
list comprehension. Here’s the example given below:
list comprehension, where each element is equal to
(i + j) % 2 , which is 0 if the row number i plus the column number j is odd (to create the white squares in the checkerboard pattern), and 1 if it’s even (to create the black squares).
Then, it converts the simple list into NumPy array.