I am lately trying to take on coding again. It had always been a part of my life since my early years when I learned to program a Tandy Color Computer at the age of 8, the good old days.
Having already programed in Java, C# and of course BASIC, I thought it would be a great idea to learn Python since I have great interest in data science and machine learning, and those two topics seem to have an avid community within Python coders.
For one of my early quick programming tasks, I decided to code Conway's Game of Life, a very simple cellular automata that basically plays itself.
The game consists of a grid of n size, and within each block of the grid a cell could either be dead or alive according to these rules:
- If a cell has less than 2 neighbors, meaning contiguous alive cells, the cell will die of loneliness
- If a cell has more than 3 neighbors, it will die of overpopulation
- If an empty block has exactly 3 contiguous alive neighbors, a new cell will be born in that spot
- If an alive cell has 2 or 3 alive neighbors, it continues to live
To make it more of a challenge I also decided to implement an "sparse" method of recording the game board, this means that instead of the typical 2d array representing the whole board, I will only record the cells which are alive. Saving a lot of memory space and processing time, while adding some spice to the challenge.
The trickiest part was figuring out how to calculate which empty blocks had exactly 3 alive neighbors so that a new cell will spring to life there, this is trivial in the case of recording the whole grid, because we just iterate all over the board and find the alive neighbors of ALL the blocks in the grid, but in the case of only keeping the alive cells proved quite a challenge.
In the end the algorithm was as follows:
- Iterate through all the alive cells and mark all the neighboring cells of each as having +1 neighbor each time a particular cell is encountered.
- This way, for each neighboring alive cell the counter of the particular block will increase, and in the end it will contain the total number of live cells.
I found it very interesting to implement the Game of Life like this, quite a refreshing challenge.