2019 FRQ 4 Post
2019 FRQ 4 post for AP CSA
The LightBoard class models a two-dimensional display of lights, where each light is either on or off, as represented by a Boolean value. You will implement a constructor to initialize the display and a method to evaluate a light.
public class LightBoard {
// 2D array storing all of the boolean light values (true indicates a light is on, while false indicates a light is off)
private boolean[][] lights;
// Constructor that initializes all of the random boolean values in the 2D array. Each light has a 40% chance of being on
public LightBoard(int numRows, int numCols) {
lights = new boolean[numRows][numCols];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
int randNumber = (int) Math.floor(Math.random() * 10) + 1;
// Use of ternary operator to concise code
boolean boolValue = (randNumber <= 4) ? true : false;
lights[i][j] = boolValue;
}
}
}
// boolean method that returns false if the selected light is on and if the number of lights that are on in its column is even
// returns true if the selected light is off and if the number of lights that are on in its column is divisible by 3 (Note that 0 is divisible by any number except itself)
// returns lightStatus if the previous 2 conditions are not met
public boolean evaluateLight(int row, int col) {
boolean lightStatus = lights[row][col];
int lightOnCount = 0;
for (int i = 0; i < lights[col].length; i++) {
if (lights[i][col] == true) {
lightOnCount++;
}
}
if (lightStatus == true && lightOnCount % 2 == 0) {
return false;
} else if (lightStatus == false && lightOnCount % 3 == 0) {
return true;
}
return lightStatus;
}
// main tester method for running the code in the LightBoard class
public static void main(String[] args) {
LightBoard myObj = new LightBoard(4, 4);
for (int x = 0; x < myObj.lights.length; x++) {
for (int y = 0; y < myObj.lights[x].length; y++) {
System.out.print(myObj.lights[x][y] + " ");
}
System.out.println("");
}
System.out.println("");
System.out.println("evaluateLight method output: " + myObj.evaluateLight(1, 1));
}
}
LightBoard.main(null);