Initially, there is a grid with some cells which may be alive or dead. Our task is to generate the next generation of cells based on the following rules:
Examples:
The ‘*’ represents an alive cell and the ‘.’ represents a dead cell.
Input : .
. **.
. *.
.
.
Output: .
. **.
. **.
.
.
.
Input : .
. **.
. *.
.
.
. **.
..**.
. *.
. *.
.
Output: .
. **.
. **.
.
.
..***.
..**.
. **.
.
.
Here is a simple Java implementation of the Game Of Life. Grid is initialized with 0’s representing the dead cells and 1’s representing alive cells. The generate() function loops through every cell and counts its neighbors. Based on that values, the aforementioned rules are implemented. The following implementation ignores the edge cells as it is supposed to be played on an infinite plane.
Implementation:
Python3
JavaScript
Initial Stage: ----- ----- ----- ----- : 1 : 0 : 1 : 1 : ----- ----- ----- ----- : 1 : 1 : 0 : 0 : ----- ----- ----- ----- : 1 : 1 : 0 : 1 : ----- ----- ----- ----- : 0 : 1 : 1 : 0 : ----- ----- ----- ----- : 0 : 0 : 0 : 0 : ----- ----- ----- ----- Next Generation: ----- ----- ----- ----- : 1 : 0 : 1 : 0 : ----- ----- ----- ----- : 0 : 0 : 0 : 1 : ----- ----- ----- ----- : 0 : 0 : 0 : 0 : ----- ----- ----- ----- : 1 : 1 : 1 : 0 : ----- ----- ----- ----- : 0 : 0 : 0 : 0 : ----- ----- ----- -----
Time Complexity : O(r*c), where r is the number of rows and c is the number of columns.
Auxiliary Space : O(r*c), since r*c extra space has been taken.
The above implementation is very basic. Try coming up with a more efficient implementation and be sure to comment below. Also for fun try creating your own rule for cellular Automata.
Conway’s Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation, etc.