I'm trying to solve conway game of life but I think I'm stuck. I'm counting the surrounding cells which I think I'm getting it correctly. However, when I assign those numbers to a temp_board and when I print temp_board, the values are all wrong.
I put it into the temp_board to evolve to the next generation. I know this is not the best code but I'm trying to iterate so I'm trying to solve it in the simplest way first.
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0]) if m else 0
temp_board = [[0] * n] * m
def count_cell(i, j):
list_of_tuples = [(i-1, j-1), (i-1, j), (i-1, j+1),
(i, j-1), (i, j), (i, j+1),
(i+1, j-1), (i+1, j), (i+1, j+1)]
count = 0
for l in list_of_tuples:
x, y = l
if x >= 0 and y >= 0 and x < m and y < n:
if x is not i or y is not j:
if board[x][y] == 1:
count += 1
return count
for i in range(m):
for j in range(n):
cell = board[i][j]
count = count_cell(i, j)
temp_board[i][j] = count
#print('(%s, %s) has %s' % (i, j, count))
print(temp_board)
"""
if cell == 1:
if count < 2:
temp_board[i][j] = 0
elif count is 3 or count is 2:
temp_board[i][j] = 1
elif count > 3:
temp_board[i][j] = 0
else:
if count == 3:
temp_board[i][j] = 1
"""
board = [[0,0,0,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,1,0,0],
[0,0,0,0,0]]
Solution().gameOfLife(board)
This is the result
➜ game-of-life git:(master) ✗ python main.py
0
1
1
1
0
0
2
1
2
0
0
3
2
3
0
0
2
1
2
0
0
1
1
1
0
[[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]]
The weird thing is when I print each cell count, it's all correct. But when I print the temp_board, it's all wrong. I'm sure I miss something obvious.