Part A

Write the constructor for the LightBoard class, which initializes lights so that each light is set to on with a 40% probability. The notation lights[r][c] represents the array element at row r and column c. Complete the LightBoard constructor below. /* Constructs a LightBoard object having numRows rows and numCols columns. Precondition: numRows > 0, numCols > 0 Postcondition: each light has a 40% probability of being set to on./ public LightBoard(int numRows, int numCols)

public LightBoard(int numRows, int numCols) {
    lights = new boolean[numRows][numCols];
    for (int r = 0; r < numRows; r++) {
        for (int c = 0; c < numCols; c++) {
            double onoff = Math.random();
            lights[r][c] = onoff < 0.4;
        }
    }
}
  • creates a new array called lights with booleans
  • sets all values based on the 40% probability

Part B

Write the method evaluateLight, which computes and returns the status of a light at a given row and column based on the following rules.

1. If the light is on, return false if the number of lights in its column that are on is even, including
the current light.
2. If the light is off, return true if the number of lights in its column that are on is divisible by three.
3. Otherwise, return the light’s current status. 
public boolean evaluateLight(int row, int col){
    int lightsOn = 0;
    for (int r = 0; r < lights.length; r++){
        if (lights[r][col]){
            lightsOn++;
        }
    }
    if (lights[row][col] && lightsOn % 2 == 0){
        return false;
    }
    if (!lights[row][col] && lightsOn % 3 == 0){
        return true;
    }
    return lights[row][col];
}
  • goes to specified column of the array
  • returns true/false depending on if statements or if the light is on/off