Program for Conway's Game Of Life - GeeksforGeeks

26 Apr, 2022
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:  
Any live cell with fewer than two live neighbors dies as if caused by underpopulation.Any live cell with two or three live neighbors lives on to the next generation.Any live cell with more than three live neighbors dies, as if by overpopulation.Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Any live cell with fewer than two live neighbors dies as if caused by underpopulation.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by overpopulation.
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.  
C
Java
Python3
C#
Javascript
#include <stdio.h>#include <stdlib.h> //change row and column value to set the canvas sizeint row = 5;int col = 4; //creates row boundaryint row_line(){    printf("\n");    for(int i=0; i<col; i++){printf(" -----");}    printf("\n");} //returns the count of alive neighboursint count_live_neighbour_cell(int a[row][col], int r, int c){    int i, j, count=0;    for(i=r-1; i<=r+1; i++){        for(j=c-1;j<=c+1;j++){            if((i==r && j==c) || (i<0 || j<0) || (i>=row || j>=col)){                continue;            }            if(a[i][j]==1){                count++;            }        }    }    return count;} int main(){       int a[row][col], b[row][col];    int i,j;    int neighbour_live_cell;     //generate matrix canvas with random values (live and dead cells)    for(i=0; i<row; i++){        for(j=0;j<col;j++){            a[i][j] = rand() % 2;        }    }         //print array matrix    printf("Initial Stage:");    row_line();    for(i=0; i<row; i++){        printf(":");        for(j=0;j<col;j++){            printf("  %d  :",a[i][j]);        }        row_line();    }     //next canvas values based on live neighbour count    for(i=0; i<row; i++){        for(j=0;j<col;j++){            neighbour_live_cell = count_live_neighbour_cell(a,i,j);            if(a[i][j]==1 && (neighbour_live_cell==2 || neighbour_live_cell==3)){                b[i][j]=1;            }             else if(a[i][j]==0 && neighbour_live_cell==3){                b[i][j]=1;            }             else{                b[i][j]=0;            }        }    }     //print next generation    printf("\nNext Generation:");     row_line(row);    for(i=0; i<row; i++){        printf(":");        for(j=0;j<col;j++){            printf("  %d  :",b[i][j]);        }        row_line(row);    }     return 0;} /*###################################### OUTPUT ####################################Initial Stage: ----- ----- ----- -----:  1  :  1  :  0  :  0  : ----- ----- ----- -----:  1  :  0  :  0  :  0  : ----- ----- ----- -----:  0  :  0  :  1  :  1  : ----- ----- ----- -----:  1  :  1  :  1  :  1  : ----- ----- ----- -----:  1  :  0  :  1  :  0  : ----- ----- ----- ----- Next Generation: ----- ----- ----- -----:  1  :  1  :  0  :  0  : ----- ----- ----- -----:  1  :  0  :  1  :  0  : ----- ----- ----- -----:  1  :  0  :  0  :  1  : ----- ----- ----- -----:  1  :  0  :  0  :  0  : ----- ----- ----- -----:  1  :  0  :  1  :  1  : ----- ----- ----- -----   *///This code is contributed by adisg25 - Aditya Singh
// A simple Java program to implement Game of Lifepublic class GameOfLife{    public static void main(String[] args)    {        int M = 10, N = 10;         // Initializing the grid.        int[][] grid = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },            { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }        };         // Displaying the grid        System.out.println("Original Generation");        for (int i = 0; i < M; i++)        {            for (int j = 0; j < N; j++)            {                if (grid[i][j] == 0)                    System.out.print(".");                else                    System.out.print("*");            }            System.out.println();        }        System.out.println();        nextGeneration(grid, M, N);    }     // Function to print next generation    static void nextGeneration(int grid[][], int M, int N)    {        int[][] future = new int[M][N];         // Loop through every cell        for (int l = 0; l < M; l++)        {            for (int m = 0; m < N; m++)            {                // finding no Of Neighbours that are alive                int aliveNeighbours = 0;                for (int i = -1; i <= 1; i++)                    for (int j = -1; j <= 1; j++)                      if ((l+i>=0 && l+i<M) && (m+j>=0 && m+j<N))                        aliveNeighbours += grid[l + i][m + j];                 // The cell needs to be subtracted from                // its neighbours as it was counted before                aliveNeighbours -= grid[l][m];                 // Implementing the Rules of Life                 // Cell is lonely and dies                if ((grid[l][m] == 1) && (aliveNeighbours < 2))                    future[l][m] = 0;                 // Cell dies due to over population                else if ((grid[l][m] == 1) && (aliveNeighbours > 3))                    future[l][m] = 0;                 // A new cell is born                else if ((grid[l][m] == 0) && (aliveNeighbours == 3))                    future[l][m] = 1;                 // Remains the same                else                    future[l][m] = grid[l][m];            }        }         System.out.println("Next Generation");        for (int i = 0; i < M; i++)        {            for (int j = 0; j < N; j++)            {                if (future[i][j] == 0)                    System.out.print(".");                else                    System.out.print("*");            }            System.out.println();        }    }}
# A simple Python program to implement Game of Life # driver program # Function to print next generationdef nextGeneration(grid, M, N):    future = [[0 for i in range(N)] for j in range(M)]     # Loop through every cell    for l in range(M):        for m in range(N):                         # finding no Of Neighbours that are alive            aliveNeighbours = 0            for i in range(-1,2):                for j in range(-1,2):                    if ((l+i>=0 and l+i<M) and (m+j>=0 and m+j<N)):                        aliveNeighbours += grid[l + i][m + j]             # The cell needs to be subtracted from            # its neighbours as it was counted before            aliveNeighbours -= grid[l][m]             # Implementing the Rules of Life             # Cell is lonely and dies            if ((grid[l][m] == 1) and (aliveNeighbours < 2)):                future[l][m] = 0             # Cell dies due to over population            elif ((grid[l][m] == 1) and (aliveNeighbours > 3)):                future[l][m] = 0             # A new cell is born            elif ((grid[l][m] == 0) and (aliveNeighbours == 3)):                future[l][m] = 1             # Remains the same            else:                future[l][m] = grid[l][m]      print("Next Generation")    for i in range(M):        for j in range(N):            if (future[i][j] == 0):                print(".",end="")            else:                print("*",end="")        print() M,N = 10,10 # Initializing the grid.grid = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]] # Displaying the gridprint("Original Generation")for i in range(M):    for j in range(N):                if(grid[i][j] == 0):            print(".",end = "")        else:            print("*",end = "")    print()print()nextGeneration(grid, M, N) # This code is contributed by shinjanpatra
// A simple C# program to implement// Game of Lifeusing System; public class GFG {         public static void Main()    {        int M = 10, N = 10;         // Initializing the grid.        int[,] grid = {            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 },            { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },            { 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }        };         // Displaying the grid        Console.WriteLine("Original Generation");        for (int i = 0; i < M; i++)        {            for (int j = 0; j < N; j++)            {                if (grid[i,j] == 0)                    Console.Write(".");                else                    Console.Write("*");            }            Console.WriteLine();        }        Console.WriteLine();        nextGeneration(grid, M, N);    }     // Function to print next generation    static void nextGeneration(int [,]grid,                               int M, int N)    {        int[,] future = new int[M,N];         // Loop through every cell        for (int l = 1; l < M - 1; l++)        {            for (int m = 1; m < N - 1; m++)            {                                 // finding no Of Neighbours                // that are alive                int aliveNeighbours = 0;                for (int i = -1; i <= 1; i++)                    for (int j = -1; j <= 1; j++)                        aliveNeighbours +=                                grid[l + i,m + j];                 // The cell needs to be subtracted                // from its neighbours as it was                // counted before                aliveNeighbours -= grid[l,m];                 // Implementing the Rules of Life                 // Cell is lonely and dies                if ((grid[l,m] == 1) &&                            (aliveNeighbours < 2))                    future[l,m] = 0;                 // Cell dies due to over population                else if ((grid[l,m] == 1) &&                             (aliveNeighbours > 3))                    future[l,m] = 0;                 // A new cell is born                else if ((grid[l,m] == 0) &&                            (aliveNeighbours == 3))                    future[l,m] = 1;                 // Remains the same                else                    future[l,m] = grid[l,m];            }        }         Console.WriteLine("Next Generation");        for (int i = 0; i < M; i++)        {            for (int j = 0; j < N; j++)            {                if (future[i,j] == 0)                    Console.Write(".");                else                    Console.Write("*");            }            Console.WriteLine();        }    }} // This code is contributed by Sam007.
<script> // A simple JavaScript program to implement Game of Life // driver program // Function to print next generationfunction nextGeneration(grid, M, N){         let future = new Array(M);    for(let i = 0; i < M; i++){        future[i] = new Array(N).fill(0);    }     // Loop through every cell    for(let l=0;l<M;l++){        for(let m=0;m<N;i++){                         // finding no Of Neighbours that are alive            let aliveNeighbours = 0            for(let i = -1; i < 2; i++)            {                for(let j = -1; j < 2; j++)                {                    if ((l + i >= 0 && l + i < M) && (m + j >= 0 && m + j < N))                        aliveNeighbours += grid[l + i][m + j]                }            }             // The cell needs to be subtracted from            // its neighbours as it was counted before            aliveNeighbours -= grid[l][m]             // Implementing the Rules of Life             // Cell is lonely and dies            if ((grid[l][m] == 1) && (aliveNeighbours < 2))                future[l][m] = 0             // Cell dies due to over population            else if ((grid[l][m] == 1) && (aliveNeighbours > 3))                future[l][m] = 0             // A new cell is born            else if ((grid[l][m] == 0) && (aliveNeighbours == 3))                future[l][m] = 1             // Remains the same            else                future[l][m] = grid[l][m]        }    }     document.write("Next Generation","</>")    for(let i = 0; i < M; i++){        for(let j = 0; j < N; j++){            if (future[i][j] == 0)                document.write(".")            else                document.write("*")        }        document.write("</br>")    }} let M = 10,N = 10 // Initializing the grid.let grid = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 ],    [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]] // Displaying the griddocument.write("Original Generation","</br>")for(let i = 0; i < M; i++){    for(let j = 0; j < N; j++)    {                 if(grid[i][j] == 0)            document.write(".")        else            document.write("*")    }    document.write("</br>")}document.write("</br>")nextGeneration(grid, M, N) // This code is contributed by shinjanpatra </script>
Output:  
Original Generation
..........
...**.....
....*.....
..........
..........
...**.....
..**......
.....*....
....*.....
..........

Next Generation
..........
...**.....
...**.....
..........
..........
..***.....
..**......
...**.....
..........
..........
The above implementation is very basic. Try coming up with 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.This article is contributed by Vaibhav Mehta. If you like GeeksforGeeks and would like to contribute, you can also mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sam007
adisg25
surinderdawra388
abhisheknm99
shinjanpatra
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s
Program to multiply two matrices
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Python program to multiply two matrices