Can anyone offer a simplified method of creating Conway's Game of life using nested for loops?

2 views (last 30 days)
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
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).

Sign in to comment.

Accepted Answer

Guillaume
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
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
Anthony
Anthony on 12 Nov 2014
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Conway's Game of Life in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!