2D Arrays Homework
import java.util.Random;
private int MAX; // given var
int[][] grid = new int[3][3];
public void repopulate() {
int num;
for(int row = 0; row < grid.length; row++) {
for(int col = 0; col < grid[0].length; col++) { // iterate through grid
num = ((int)(Math.random()) * (MAX/10) + 1) * 10; // generate a new random int that is between 1 and MAX, and divisible by 10
while (num % 100 == 0) { // while num is divisible by 0:
num = ((int)(Math.random()) * (MAX/10) + 1) * 10; // generate a new random int until the remainder is no longer 0
}
grid[row][col] = num; // set the random value in the position and continue looping
}
}
}
repopulate();
private int[][] grid = { // Expected output: 3
{1,4,7},
{2,5,8},
{3,6,9}
};
private int[][] grid2 = { // Expected output: 4
{1,1,1,1,1,10},
{2,2,2,2,2,2},
{3,30,3,3,3,3},
{4,4,4,4,4,4}
};
public int countIncreasingCols(int[][] grid) {
int cols = 0; // initialize cols which holds the number of
boolean add = true;
for(int col = 0; col <= grid[0].length-1; col++) { // column-row for looping
for(int row = grid.length-1; row > 0; row--) {
if(grid[row][col] < grid[row-1][col]) add = false; // if the current position is less than the position one row up (checking along 1 column), set add to false
}
if(add) cols++; // if add remains true throughout the loop, increment cols
add = true; // reset add to true
}
return cols; // return after finishing loop
}
System.out.println("Number of increasing columns in grid: " + countIncreasingCols(grid) + " Number of increasing columns in grid2: " + countIncreasingCols(grid2))
Number of increasing columns in grid: 3 Number of increasing columns in grid2: 4