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
Best Answer
Josh - from Game of Life, there are four rules that need to be applied given the state of the cell, three of which are appropriate if the cell is live and one for when the cell is dead. So you have two "objects" to consider - the state of the cell and the rule to apply. Typically, I would use a switch statement only if I had one object (or its state) to be concerned with. In this case, you could use a switch statement on the state of the cell and then, if needed, use a switch statement on the neighbours. Something like
Note that isCellAlive indicates the state of the cell (live or dead, true or false) and that numNeighbours indicates the number of live cells or neighbours.
So are there any advantages to using a switch in the above? I'm not sure. It does work because we only have a small set of integers that are appropriate for each of the cases (0 or 1, or 2 or 3). If you had larger ranges (say all positive integers between 1 and 25) then an if condition would be easier to use than doing case {1,2,3,4,etc.}. I think that the above code is as readable this way or if we were to use an if/elseif block.