-
Notifications
You must be signed in to change notification settings - Fork 0
/
Conways_Game_of_Life_Unlimited_Edition.py
57 lines (39 loc) · 1.35 KB
/
Conways_Game_of_Life_Unlimited_Edition.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from itertools import product
def matrix_to_set(matrix):
s = set()
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]:
s.add((i, j))
return s
def set_to_table(s):
if not set:
mi = mj = ni = nj = 0
else:
mi = min(map(lambda x: x[0], s))
mj = min(map(lambda x: x[1], s))
ni = max(map(lambda x: x[0], s))
nj = max(map(lambda x: x[1], s))
table = [[0 for _ in range(nj - mj + 1)] for _ in range(ni - mi + 1)]
for (i, j) in s:
table[i - mi][j - mj] = 1
return table
def get_generation(cells, generations):
_cells = matrix_to_set(cells)
for _ in range(generations):
cells_neighbours = set()
new_cells = set()
for (i, j) in _cells:
for (di, dj) in product((-1, 0, 1), (-1, 0, 1)):
cells_neighbours.add((i + di, j + dj))
for (i, j) in cells_neighbours:
neighbours = 0
for (di, dj) in product((-1, 0, 1), (-1, 0, 1)):
if (i + di, j + dj) in _cells and (di, dj) != (0, 0):
neighbours += 1
if neighbours == 3:
new_cells.add((i, j))
elif neighbours == 2 and (i, j) in _cells:
new_cells.add((i, j))
cells = new_cells
return set_to_table(cells)