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!