Game of Life rules using switch statement.
Show older comments
Hi could someone please help me write out the game of life rules using switch statement. i know how to do it using if else if (which is all i can find on internet) but there aren't any that use switch. is it possible to use switch? are there any advantages?
say the number of neighbours is called counts. what would I call the new count (i.e how would i update the world?)
would it be:
switch n
case 1 counts= 1, newcount=0??
obviously not thats way to easy
Accepted Answer
More Answers (1)
John D'Errico
on 10 Oct 2015
Edited: John D'Errico
on 10 Oct 2015
Personally, I'd use conv2. What happens if you use the convolution kernel
K = [1 1 1;1 0 1;1 1 1];
1. A live cell will die if it has less than 2 or more than 3 live neighbors.
2. A dead cell is born if it has exactly 3 neighbors.
If the above rules are not met, then the cell stays in the same state it was in before.
Thus, something vaguely like this:
count = conv2(M,K,'same');
born = (M == 0) & (count == 3);
dies = (M == 1) & ((count < 2) | (count > 3));
M(born) = 1;
M(dies) = 0;
Now, just repeat until you get bored, by wrapping a loop around the code fragment above.
You can see one iteration work as follows:
M = double(rand(6) > .5)
M =
0 1 1 0 1 0
1 0 1 0 1 0
1 0 1 1 1 1
1 1 1 0 0 0
1 1 1 0 0 1
0 0 1 0 1 1
count = conv2(M,K,'same')
count =
2 3 2 4 1 2
2 6 4 7 4 4
3 7 4 5 3 2
4 7 5 5 4 3
3 6 4 4 3 2
2 4 2 3 2 2
born = (M == 0) & (count == 3)
born =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 1
0 0 0 0 1 0
0 0 0 1 0 0
dies = (M == 1) & ((count < 2) | (count > 3))
dies =
0 0 0 0 1 0
0 0 1 0 1 0
0 0 1 1 0 0
1 1 1 0 0 0
0 1 1 0 0 0
0 0 0 0 0 0
M(born) = 1;
M(dies) = 0;
M
M =
0 1 1 0 0 0
1 0 0 0 0 0
1 0 0 0 1 1
0 0 0 0 0 1
1 0 0 0 1 1
0 0 1 1 1 1
Categories
Find more on Conway's Game of Life in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!