Initialize an n x n matrix in 1 line.
When I was trying to make a simple tic-tac-toe game in React, I needed to initialize a 3 by 3 matrix to represent the game state. It was surprisingly hard to find what I needed online, so I decided to figure it out myself and share what I discovered.
The Naive Way
When the matrix is small, and there isn’t a lot of complex logic to manage, this way is often good enough.
The Better Way
The naive way is good for the example of Tic-Tac-Toe, but what about a 50 x 50 grid? Or what if you want each tile to store additional information that can’t be represented by a number?
Now even if you want each cell to hold some specific logic, it’s super easy to do so. For example:
Hope you found this useful!