Page 1 of 1

JAVA 2. Complete the following class named Life from Convey's “Game of Life”. You can add more field variables if requir

Posted: Mon Jun 06, 2022 1:18 pm
by answerhappygod
JAVA
2. Complete the following class named Life from Convey's
“Game of Life”. You can add more field variables if required. For
hint you could use nextMap[][]
/**
* Life stores the internal representation of a cellular
world where a cell can be empty or occupied.
* An occupied cell dies (becomes empty) if it has (1) one
or no neighbours or (2) over 3
neighbours.
* An occupied cell with 2 or 3 neighbours survives. An empty
cell that has 3 neighbours becomes occupied.
*/ public class Life
{ private
boolean[][] map;
private int width,
height;
/**
* Constructor for Life. Initializes the width and height
variables.
* Creates the map array and initializes it by calling the
"initializeMap" method.
*/
public Life(int width, int height, double probability)
{
// TODO (a) [3
marks] write the constructor to initialize the field variables
including map
}
/**
* A method that initializes map randomly with the given
occupied probability
* /
private void initializeMap(double
probability)
{
// TODO (b)
[2marks] write the method
}
/**
* Uses numNeighbours to get the neighbours of
cell(i,j) and updates
* the map according to the rules of the game.
*/
public void nextGeneration()
{
// TODO (c) [5 marks] Write your code
such that it does not produce “garbage” objects.
for (int i = 0; i < width; i++)
for (int j = 0; j <
height; j++)
{
int z =
numNeighbours(i, j);
if (z == 2)
nextMap[j] = map[j];
else
nextMap[j] = z == 3; //I
don't understand this line in the given solution works. Could you
explain how this line works or try to solve this method for 5
marks in a different way ? . Also for info this method solution
does work.
}
boolean[][] swap = map;
map = nextMap;
nextMap = swap;
}
/**
* Returns the number of neighbours of cell(i,j)
*/
private int numNeighbours(int i, int j)
{
// Assume this code is provided and works.
}
}