Can anyone offer a simplified method of creating Conway's Game of life using nested for loops?
4 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Guillaume
2014 年 11 月 12 日
編集済み: Guillaume
2014 年 11 月 12 日
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).
採用された回答
Guillaume
2014 年 11 月 12 日
編集済み: Guillaume
2014 年 11 月 12 日
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 件のコメント
Guillaume
2014 年 11 月 12 日
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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Conway's Game of Life についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!