# Different ways to create a nxn matrix and fill it with a checkerboard pattern

The checkerboard pattern represents a set of 64 black and white squares. Similar to the pattern in the chessboard. In real-time, checkerboard patterns are extensively used to create a no pixel blank area(blank grid).

Checkerboard pattern can be represented easily using an array of size 8*8. We can use the numpy module to create an array and fill it with a checkerboard pattern using various functions from numpy.

In this article, let’s learn how to create an n*n matrix in a checkerboard pattern.

NOTE: If you don’t have numpy, you can install it using the below command:

`pip install numpy`

## Solution 1: Using np.tile()

We create an array [[0,1],[1,0]] and repeat it n/2 times along both axes.

For example, to create an 8*8 matrix, we created an array and multiply it 4 times.

Refer to the below diagram to understand it better.

Process finished with exit code 1

Now that we’ve understood, let’s try to implement it using np.tile()

```import numpy as np

a=np.array([[0,1],[1,0]])

#construct the checker board by repeating the above array 4 times in both dimensions
checkerboard=np.tile(a,(4,4))
print(checkerboard)```

Output:

```[[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]]```

## Solution 2: Using Slicing

We create an array with zeros of size n*n.

The first row should start from zero. From the second row( index 1) onwards, for every alternate row, we set the value 1 to every alternate column.

```[[0 0 0 0 0 0 0 0]
[1 0 1 0 1 0 1 0]
[0 0 0 0 0 0 0 0]
[1 0 1 0 1 0 1 0]
[0 0 0 0 0 0 0 0]
[1 0 1 0 1 0 1 0]
[0 0 0 0 0 0 0 0]
[1 0 1 0 1 0 1 0]]```

Now, for every alternate row(starting from row 1,i.e index 0) we set 1 to every alternate column starting from column 2,i.e index 1

```[[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]]```

Let’s implement the slicing logic to come up with an 8*8 checkerboard.

```import numpy as np
arr=np.zeros((8,8),dtype=int)
arr[1::2,::2]=1
arr[::2,1::2]=1
print(arr)```

Output:

```[[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]]```

## Conclusion

In this article, we’ve learned different ways to create an 8*8 matrix with a checkerboard pattern. We hope this article has been informative. Thanks for Reading. Come back to us for more interesting content.