ANONYMOUS wrote:
Hi, I'm having issues getting the simulating the step working for my version of game of life.
At the moment my method clones the grid, then reads off this clone to edit the original grid's values however it does not in the intended way. Should my method be following the answers more closely?
You should try to solve the problem yourself without looking at the answers first, so no, there is no need to follow the example answers exactly.
It is not entirely clear what you mean by "it does not [edit the grid] in the intended way", but I might have a guess.
Assuming by "clones the grid" you mean you are literally using grid.clone()
, be careful, as this only performs a shallow copy, and since grid
is actually an array of arrays, it will clone the outer array, but the contents of that outer array will just be references to the same inner arrays as in grid
, and so writing to the cloned grid will write to the original as well.
Additionally, looking at the answer, I somewhat understand what the method is but I'm unsure what is being down with the operation:
neighbors += grid[l][j] ? 1 : 0;
Is this used to convert the Boolean to a number 1 if it's true and 0 if false?
Yes, this is a ternary expression.
Ternary expressions appear in lots of programming languages in various forms, but this is the syntax used by Java and other C-style languages.
The general form is that condition ? tvalue : fvalue
evaluates to tvalue
if condition
is true and fvalue
if it is false.
Here it is being used as a convenient shorthand to enable counting the number of neighbours that are alive.