A matrix question usually shows up on the AP Computer Science exam, and in 2019 the last question had that matrix.

What you were give was a matrix of boolean values which represent lights on or off on a rectangular board. `true`

represents a light that’s on and `false`

is a light that’s off.

The `LightBoard`

class has an instance variable `boolean[][] lights`

that holds the boolean values. You’ll be working with this instance variable in both methods to implement.

Like most AP FRQs the constructor asks you to set the instance variables. In this case we need to create the matrix and randomly fill it with `true`

and `false`

values so that each cell has a 40% probability of being `true`

.

```
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++) {
lights[r][c] = Math.random() < 0.4;
}
}
```

The first line instantiates and sizes `lights`

to `numRows`

rows and `numCols`

columns. Going off of previous problems, I assume that many students forgot this line. If it’s not there `lights`

would be `null`

.

Next the code iterates through each cell in the matrix and uses `Math.random`

to take care of the 40% probability. Remember that `Math.random()`

returns a number in the range 0.0 to 1.0, exclusive of 1.0. So it should return something < 0.4 40% of the time.

Part B asks you to evaluation a light based on these conditions.

- If the light is on and there are an even number of lights in that column, return
`false`

. - If the light is off and there are a multiple of 3 lights on in that column, return
`true`

. - If neither condition, return the value of the light.

```
public boolean evaluateLight(int row, int col) {
int onInCol = 0;
for (int r=0; r<lights.length; r++) {
if (lights[r][col]) {
onInCol++;
}
}
if (lights[row][col] && onInCol % 2 == 0) {
return false;
} else if (!lights[row][col] && onInCol % 3 == 0) {
return true;
} else {
return lights[row][col];
}
}
```

Since we’ll need the number of on lights in `col`

several times it’s best to go ahead and calculate that first. I did that and stored it in the `onInCol`

variable.

With that we can now build a set of `if`

statements that takes care of returning the right value based on the conditions above.

This site contains affiliate links. If you click an affiliate link and make a purchase we may get a small
commission. It doesn't affect the price you pay, but it is something we must disclose.