Can anyone offer a simplified method of creating Conway's Game of life using nested for loops?
2 views (last 30 days)
Show older comments
Need help evaluating array to follow the rules of Conway's game of life. Living cell 4 or more neighbors.... I also need the program to move one generation at a time.
1 Comment
Guillaume
on 12 Nov 2014
Edited: Guillaume
on 12 Nov 2014
What difficulty are you facing? It's not particularly difficult to code. You just have to count the number of neighbours of a cell and turn it on or off depending on that count.
The number of neighbours can be calculated any way you want, either by scanning all of them for each cell (a bit wasteful) or using 2d convolution (with a [1 1 1; 1 0 1; 1 1 1] kernel).
Accepted Answer
Guillaume
on 12 Nov 2014
Edited: Guillaume
on 12 Nov 2014
It's actually dead easy to implement in matlab, and you don't need for loops.
m = randi(2, 500) - 1;
while true %use control C to stop
imshow(m);
drawnow;
neighbours = conv2(m, [1 1 1; 1 0 1; 1 1 1], 'same');
m = double((m & neighbours == 2) | neighbours == 3);
end
9 Comments
Guillaume
on 12 Nov 2014
I can't see any attachment.
The whole rules are encompassed in the one line:
array = double((array & neighbours == 2) | neighbours == 3)
A cell is live iff
- it is already live and has two neighbours
- or it has three neighbours
It covers both the keep alive rule (two or three neighbours), and the birth rule (3 neighbours).
You can replace that with for loops and if statements, but once again why?
for rowm = 1:size(m, 1)
for colm = 1:size(m, 2)
if (m(rowm, colm) == 1 && neighbours(rowm, colm) == 2) || neighbours(rowm, colm) == 3
m(rowm, colm) = 1;
else
m(rowm, colm) = 0;
end
end
end
More Answers (0)
See Also
Categories
Find more on Conway's Game of Life in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!