Inicialmente, hay una cuadrícula con algunas celdas que pueden estar vivas o muertas. Nuestra tarea es generar la próxima generación de células en base a las siguientes reglas:
- Cualquier celda viva con menos de dos vecinas vivas muere como si fuera causada por la falta de población.
- Cualquier celda viva con dos o tres vecinos vivos vive en la próxima generación.
- Cualquier célula viva con más de tres vecinos vivos muere, como por sobrepoblación.
- Cualquier célula muerta con exactamente tres vecinos vivos se convierte en una célula viva, como por reproducción.
Ejemplos:
El ‘*’ representa una celda viva y el ‘.’ representa una célula muerta.
Input : .......... ...**..... ....*..... .......... .......... Output: .......... ...**..... ...**..... .......... .......... .......... Input : .......... ...**..... ....*..... .......... .......... ...**..... ..**...... .....*.... ....*..... .......... Output: .......... ...**..... ...**..... .......... .......... ..***..... ..**...... ...**..... .......... ..........
Aquí hay una implementación Java simple del Juego de la Vida. La cuadrícula se inicializa con 0 que representan las celdas muertas y 1 que representan las celdas vivas. La función generar() recorre cada celda y cuenta sus vecinos. Con base en esos valores, se implementan las reglas antes mencionadas. La siguiente implementación ignora las celdas de borde ya que se supone que se juega en un plano infinito.
Implementación:
C++
#include <iostream> using namespace std; // change row and column value to set the canvas size const int row = 5; const int col = 4; // creates row boundary int row_line() { cout << endl; for (int i = 0; i < col; i++) { cout << " -----"; } cout << endl; } // returns the count of alive neighbours int 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 cout << "Initial Stage:"; row_line(); for (i = 0; i < row; i++) { cout << ":"; for (j = 0; j < col; j++) { cout << " " << 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 cout << "\nNext Generation:"; row_line(); for (i = 0; i < row; i++) { cout << ":"; for (j = 0; j < col; j++) { cout << " " << b[i][j] << " :"; } row_line(); } 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 Tapesh(tapeshdua420)
C
#include <stdio.h> #include <stdlib.h> //change row and column value to set the canvas size int row = 5; int col = 4; //creates row boundary int row_line(){ printf("\n"); for(int i=0; i<col; i++){printf(" -----");} printf("\n"); } //returns the count of alive neighbours int 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
Java
// A simple Java program to implement Game of Life public 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(); } } }
Python3
# A simple Python program to implement Game of Life # driver program # Function to print next generation def 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 grid print("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
C#
// A simple C# program to implement // Game of Life using 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.
Javascript
<script> // A simple JavaScript program to implement Game of Life // driver program // Function to print next generation function 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 grid document.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>
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 : ----- ----- ----- -----
Complejidad temporal : O(r*c), donde r es el número de filas y c es el número de columnas.
Espacio Auxiliar : O(r*c)
La implementación anterior es muy básica. Intente encontrar una implementación más eficiente y asegúrese de comentar a continuación. También, por diversión, intente crear su propia regla para autómatas celulares.
Game Of Life de Conway es un método de automatización celular creado por John Conway. Este juego se creó pensando en la biología, pero se ha aplicado en varios campos, como gráficos, generación de terreno, etc.
Este artículo es una contribución de Vaibhav Mehta . Si le gusta GeeksforGeeks y desea contribuir, también puede enviar su artículo por correo electrónico a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA