FRQ 4 - 2D Arrays
Data
public class Data {
public static final int MAX = 1000;
private int[][] grid;
public Data() {
grid = new int[4][4];
}
/**
* Fills all elements of grid with randomly generated values, as described in part (a)
* Precondition: grid is not null. grid has at least one element.
*/
public void repopulate() {
for (int i = 0; i < grid.length; i++) {
//iterates through rows
for (int j = 0; j < grid[0].length; j++) {
//then columns
int rand = (int) (Math.random() * MAX);
//returns random value within range of MAX
while (rand % 10 != 0 || rand % 100 == 0) {
rand = (int) (Math.random() * MAX);
//if the conditions are not met, keep generating random
}
grid[i][j] = rand;
//place int in grid spot
}
}
}
/**
* Returns the number of columns in grid that are in increasing order, as described in part (b)
* Precondition: grid is not null. grid has at least one element.
*/
public int countIncreasingCols() {
int columns = 0; //starts with a column count of 0
for (int j = 0; j < grid[0].length; j++) {
boolean increasing = true; //og starts with true
for (int i = 1; i < grid.length; i++) {
if (grid[i][j] < grid[i - 1][j]) {
increasing = false;
break;
//if when checking columns and rows the 2nd one is smaller, false
}
}
if (increasing) {
columns++;
//increase the column count for each one true
}
}
return columns;
}
// Tester method
public static void main(String[] args) {
Data data = new Data();
Data data2 = new Data();
data.repopulate();
data2.repopulate();
// Print the generated grids
System.out.println("Grid 1:");
for (int i = 0; i < data.grid.length; i++) {
for (int j = 0; j < data.grid[0].length; j++) {
System.out.print(data.grid[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("Grid 2:");
for (int i = 0; i < data2.grid.length; i++) {
for (int j = 0; j < data2.grid[0].length; j++) {
System.out.print(data2.grid[i][j] + " ");
}
System.out.println();
}
// Count the number of columns that are in increasing order
System.out.println();
System.out.println("----------------");
System.out.println("Number of columns in increasing order for grid 1: " + data.countIncreasingCols());
System.out.println("Number of columns in increasing order for grid 2: " + data2.countIncreasingCols());
}
}
Data.main(null);