FRQ 4 Solved
FRQ 4
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.
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++){
// 0-99 inclusive
if(((int)Math.random() * 100) <= 39){
lights[i][j] = true;
}
else{
lights[i][j] = false;
}
}
}
}
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. For example, suppose that LightBoard sim = new LightBoard(7, 5) creates a light board with the initial state shown below, where true represents a light that is on and false represents a light that is off. Lights that are off are shaded.
public boolean evaluateLight(int row, int col){
if(lights[row][col]){
int numOn = 0;
for(int i = 0; i < row; i++){
if(lights[i][col]){
numOn++;
}
}
if(numOn % 2 == 0){
return false;
}
}
if(!lights[row][col]){
int numOn2 = 0;
for(int i = 0; i < row; i++){
if(lights[i][col]){
numOn2++;
}
}
if(numOn2 % 3 == 0){
return true;
}
}
return lights[row][col];
}
/* Assign random colors and effects */
public Light() {
int maxColor = 255;
int effect = 9;
this.red = (short) (Math.random()*(maxColor+1));
this.green = (short) (Math.random()*(maxColor+1));
this.blue = (short) (Math.random()*(maxColor+1));
this.onOff();
if(!this.on){
this.effect = 0;
}
else{
this.effect = (short) (Math.random()*(effect+1));
}
}
public void onOff(){
if(((int)Math.random() * 100) <= 39){
this.on = true;
}
else{
this.on = false;
}
}
LightBoard lightBoard = new LightBoard(4, 4);
final int ROWS = 2
final int COLS = 2;