2019 FRQ 4
LightBoard
LightBoard FRQ
-
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.
-
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.
- If the light is on, return false if the number of lights in its column that are on is even, including the current light.
- If the light is off, return true if the number of lights in its column that are on is divisible by three.
- Otherwise, return the light’s current status.
import java.lang.Math;
public class LightBoard {
private boolean[][] lights;
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++) {
if (Math.random() < 0.4) {
lights[r][c] = true;
}
else {
lights[r][c] = false;
}
}
}
}
public boolean evaluateLight(int row, int col) {
int lightsOn = 0;
for (int r = 0; r<lights.length; r++) { // iterating through rows for each column
if (lights[r][col] == true) {
lightsOn++;
}
}
if (lightsOn % 2 == 0) {
return false;
}
else if (lightsOn % 3 == 0) {
return true;
}
else {
return lights[row][col];
}
}
}