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
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
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
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
Anthony
Anthony 2014년 11월 12일
Sorry. The file is attached. It is called array. I agree with you. I know it is complicated but I am supposed to be learning about nesting for loops with case statements. You don't even want to see the rest of the requirements for this program. I have to count the sum of living cells of each generation, create a plot using intrinsic function surf(x), label and color code plot, find the average of number of cells, etc.... The list goes on. Thank you for your help. I will probably post another question after I attempt to complete this grocery list of requirements for this program.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile 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!

Translated by