concerning john conway life of death , a grid ,in which there alive cells, form a pattern .
This pattern is in the positioning 0 which is called generation 0 . a loop begins and the status of cells , in each generation , change so that the pattern change during each generation.

for example :

generation | numbers of alive cells

loop gives:

0=45
1=60
2=55
3=80
4=90
.....
....

and so on

my question is :

how to know ****the numbers of alive cells** at each generation while the loop goes??**

Dani AI

Generated

was on the right track. Recording "alive cell" counts as the simulation runs is just bookkeeping; the choice of data structure decides how simple and fast that bookkeeping is. Below are three practical Python patterns you can paste into a loop to both advance the Game of Life and log the live count each generation.

Dense grid (NumPy, toroidal/wrap boundaries). grid is a 2D boolean array; grid.sum() is the live count. np.roll computes neighbor sums without Python loops:

import numpy as np

counts = []
for gen in range(max_gens):
    counts.append(int(grid.sum()))
    N = (
        np.roll(grid, 1, 0) + np.roll(grid, -1, 0) +
        np.roll(grid, 1, 1) + np.roll(grid, -1, 1) +
        np.roll(np.roll(grid, 1, 0), 1, 1) +
        np.roll(np.roll(grid, 1, 0), -1, 1) +
        np.roll(np.roll(grid, -1, 0), 1, 1) +
        np.roll(np.roll(grid, -1, 0), -1, 1)
    )
    grid = (N == 3) | (grid & (N == 2))

Sparse set (few live cells, large/virtual grid). Keep a set of (x,y) coordinates and use a Counter to tally neighbor touches; this is O(k) per generation where k is live-cell count:

from collections import Counter

counts = []
for gen in range(max_gens):
    counts.append(len(alive))
    c = Counter()
    for x,y in alive:
        for dx in (-1,0,1):
            for dy in (-1,0,1):
                if dx == 0 and dy == 0: continue
                c[(x+dx, y+dy)] += 1
    alive = {pos for pos, v in c.items() if v == 3 or (v == 2 and pos in alive)}

Loop/stability detection and cautions. To stop when a pattern repeats or dies out, store a compact key each generation (e.g. grid.tobytes() for dense or frozenset(alive) for sparse) in a dict mapping to generation; if the key reappears you found a cycle. Avoid in-place updates when computing the next state. Choose dense vs sparse based on grid occupancy, and consider specialized tools (Golly) or Hashlife if you need extremely large or long-running simulations.

Recommended Answers

All 2 Replies

I'm not quite sure I understand the question. You're simulating the game of life, so, at each step, you have a grid containing the live and dead cells, right? So just iterate over that grid and count the cells that are alive.

ok , I will try

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.