# Stride tricks for the Game of LifeΒΆ

Date: | 2010-10-18 (last modified), 2010-10-18 (created) |
---|

This is similar to [:../SegmentAxis:Segment axis], but for 2D arrays with 2D windows.

The Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970, see [1].

It consists of a rectangular grid of cells which are either dead or alive, and a transition rule for updating the cells' state. To update each cell in the grid, the state of the 8 neighbouring cells needs to be examined, i.e. it would be desirable to have an easy way of accessing the 8 neighbours of all the cells at once without making unnecessary copies. The code snippet below shows how to use the devious stride tricks for that purpose.

[1] Game of Life at Wikipedia

In [7]:

```
import numpy as np
from numpy.lib import stride_tricks
x = np.arange(20).reshape([4, 5])
xx = stride_tricks.as_strided(x, shape=(2, 3, 3, 3), strides=x.strides + x.strides)
```

In [8]:

```
x
```

Out[8]:

In [9]:

```
xx
```

Out[9]:

In [11]:

```
xx[0,0]
```

Out[11]:

In [12]:

```
xx[1,2]
```

Out[12]:

In [13]:

```
x.strides
```

Out[13]:

In [14]:

```
xx.strides
```

Out[14]:

*Section author: RobertCimrman*