Note: this is to be written in Python Rules: The game is played on a rectangular
ID: 3866124 • Letter: N
Question
Note: this is to be written in Python
Rules: The game is played on a rectangular grid. Each square on the grid can be either empty (represented by a 0 in our version) or occupied by a "living" cell (represented by a 1). At the beginning, you can specify empty and occupied cells in some way; then the game runs automatically. In each generation, the next generation is computed. A new cell is born on an empty square if it is surrounded by exactly three occupied neighbor cells. A cell dies of overcrowding if it is surrounded by four or more living neighbors, and it dies of loneliness if it is surrounded by zero or one living neighbor. A neighbor is an occupant of an adjacent square to the left, right, top, or bottom or in a diagonal direction.
The core problem to be solved in the implementation of the Game of Life is how to generate the next grid from the current grid. Your task is to write a function called nextGen which expects only one argument. That argument is a two-dimensional table (i.e., a list of lists) with m rows and n columns, representing the current grid. The elements of the table are either 0 (empty square) or 1 (occupied square). You may assume that all rows have the same number of elements.
Given the current grid, nextGen computes and returns (but does not print) a new next grid (without altering the current grid) by applying the simple rules provided above. For example, given this initial grid:
glider =
your function should work like this:
If we formatted those results nicely, we'd see a sequence like this:
Explanation / Answer
def nextGen(currentGrid):
rows=len(currentGrid)
cols=len(currentGrid[0])
#copying currentGrid into newGrid
newGrid = list(currentGrid)
occupied=0
for row in range(0,rows):
for col in range(0,cols):
#iterating through neighbours
for r in range(row-1,row+2):
for c in range(col-1,col+2):
#checking limits
if(r>-1 and r <rows and c>-1 and c<cols and r!=row and c!=col):
occupied=occupied+currentGrid[row-1][col-1]
#checking conditions
if(newGrid[row][col]==0):
if(occupied==3):
newGrid[row][col]=1
else:
if(occupied>=4):
newGrid[row][col]=0
elif(occupied==0 or occupied==1):
newGrid[row][col]=0
occupied=0
return newGrid
grid=[[0,0,0,0,0,0,0],
[0,0,1,0,0,0,0],
[0,0,0,1,0,0,0]]
newGrid=nextGen(grid)
for row in newGrid:
print(row)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.