CollegeBoard FRQ 4
public class Test {
public static void main(String[] args) {
int[][] arr = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
System.out.println("arr[0][0] = " + arr[0][0]);
System.out.println("arr[1][2] = " + arr[1][2]);
System.out.println("arr[2][1] = " + arr[2][1]);
}
}
Test.main(null);
- Element = a single value in the array
- Index = the position of the element in the array (starts from 0)
-
Array Length = the number of elements in the array
- Is public, so can be accessed in any class
- Is also final, so can’t change it after array has been created
-
Nested Loops = A nested loop is a loop within a loop, an inner loop within the body of an outer one
- an example:
public class Test {
public static void main(String[] args) {
String[][] arr = {
{ "a", "f", "g", "l" },
{ "b", "e", "h", "k" },
{ "c", "d", "i", "j" }
};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println(" ");
}
}
}
Test.main(null);
public class LightBoard {
/** The lights on the board, where true represents on and false represents off.
*/
private boolean[][] lights;
/** 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)
{ /* to be implemented in part (a) */ }
/** Evaluates a light in row index row and column index col and returns a status
* as described in part (b).
* Precondition: row and col are valid indexes in lights.
*/
public boolean evaluateLight(int row, int col)
{ /* to be implemented in part (b) */ }
// There may be additional instance variables, constructors, and methods not shown.
}
public LightBoard(int numRows, int numCols) {
lights = new boolean[numRows][numCols];
// use of nested loops to iterate through the array elements
for(int r = 0; r < lights.length; r++) {
for(int c = 0; c < lights[0].length; c++) {
if(Math.random() <= 0.4)
lights[r][c] = true;
}
}
}
public boolean evaluateLight(int row, int col) {
// sets initial to 0
int onInColumn = 0;
// finds how many lights are on
for(int r = 0; r < lights.length; r++) {
if(lights[r][col] == true) {
onInColumn++;
}
}
// decides if the conditions match true or false
if(lights[row][col]) {
if(onInColumn % 2 == 0) {
return false;
}
} else {
if(onInColumn % 3 == 0) {
return true;
}
}
return lights[row][col];
}