Program for Conway’s Game Of Life

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:

  1. Any live cell with fewer than two live neighbors dies as if caused by underpopulation.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

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
Output
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.