Horizontal Header

Shaurya Goel's CSA Github Pages

Period 3 Mr. Mortensen

Overall Explanation of 2D Arrays

A two-dimensional (2D) array in programming is a data structure that stores elements in a grid-like or tabular format, organized in rows and columns. It’s essentially an array of arrays, where each element is uniquely identified by a pair of indices: a row index and a column index.

image.png

CSA 2022 FRQ College Board

This question involves a two-dimensional array of integers that represents a collection of randomly generated data. A partial declaration of the Data class is shown. You will write two methods of the Data class.

public class Data
{
    public static final int MAX = /*  */
    private int[][] grid;

    public void repopulate() {
    // Fills all elements of grid with randomly generated values
    // Precondition: grid is not null and has at least one element
    }

    int countIncreasingCols() {
    // Returns the number of columns in grid that are in increasing order
    // Precondition: grid is not null and has at least one element
    }

    

    
}

image.png

image.png

This code uses a Random object to generate random numbers and ensures that the generated values meet the specified criteria before assigning them to the grid.

import java.util.Random;
// provides functionality for generating pseudorandom numbers
// Pseudorandom numbers are generated using an algorithm, and they appear random

public void repopulate() {
    
    if (grid == null || grid.length == 0 || grid[0].length == 0) {
        // Checks if grid has anything in it, if there is anything in the grid, and if first row of the grid exists
        // The || operator says if one of these are true then the entire expression is true
        return;
    }

    Random random = new Random();
    // create an object of this random class

    for (int row = 0; row < grid.length; row++) { //This line starts a loop that iterates over the rows of a two-dimensional array grid   // 
        // The loop variable row is initialized to 0, and the loop continues as long as row is less than the number of rows in the grid array (grid.length).
        for (int col = 0; col < grid[row].length; col++) {  // Within the outer loop, there's an inner loop that iterates over the columns of the current row (grid[row])
            // The loop variable col is initialized to 0, and the loop continues as long as col is less than the number of columns in the current row (grid[row].length).
            
            // Generate a random number between 1 and MAX (inclusive)
            int randomValue = random.nextInt(MAX) + 1;

            // Check if the value is divisible by 10 and not divisible by 100
            while (randomValue % 10 != 0 || randomValue % 100 == 0) {
                randomValue = random.nextInt(MAX) + 1;
            // if randomValue doesn't meet the conditions, a new random value is generated and assigned to randomValue. 
            }

            // Assign the generated value to the current element in the grid
            grid[row][col] = randomValue;
        }
    }
}


In summary, this code block is used to populate a two-dimensional array grid with random integer values between 1 and MAX, where each value is required to be divisible by 10 and not divisible by 100. It iterates through each row and column of the array, generating and assigning random values until the conditions are met for each element in the array.

This method iterates over each column in the grid and checks whether each column is in increasing order by comparing each element in a column with the element in the previous row. If all comparisons in a column indicate that it’s in increasing order, the count is incremented. Finally, the method returns the count of columns that meet the criteria.

import java.util.Random;

    public int countIncreasingCols() {
        // Preconditions: grid is not null and grid has at least one character

        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            // Handle invalid grid input
            return 0;
        }

        int count = 0;

        // Iterate over each column
        for (int col = 0; col < grid[0].length; col++) {
            boolean isIncreasing = true;

            // Check each row in the column
            for (int row = 1; row < grid.length; row++) {
                if (grid[row][col] < grid[row - 1][col]) {
                    // If the current element is less than the previous element in the column, it's not in increasing order
                    isIncreasing = false;
                    break;
                }
            }

            if (isIncreasing) {
                // If the column is in increasing order, increment the count
                count++;
            }
        }

        return count;
    }


import java.util.Random;

public class Data {
    public static final int MAX = 100; // Set MAX to your desired maximum value
    private int[][] grid;

    public Data(int numRows, int numCols) {
        // Initialize the grid with the specified dimensions
        grid = new int[numRows][numCols];
    }

    public int countIncreasingCols() {
        // Preconditions: grid is not null and grid has at least one character

        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            // Handle invalid grid input
            return 0;
        }

        int count = 0;

        // Iterate over each column
        for (int col = 0; col < grid[0].length; col++) {
            boolean isIncreasing = true;

            // Check each row in the column
            for (int row = 1; row < grid.length; row++) {
                if (grid[row][col] < grid[row - 1][col]) {
                    // If the current element is less than the previous element in the column, it's not in increasing order
                    isIncreasing = false;
                    break;
                }
            }

            if (isIncreasing) {
                // If the column is in increasing order, increment the count
                count++;
            }
        }

        return count;
    }
    
    public void repopulate() {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            System.out.println("The grid is empty. Cannot populate.");
            return;
        }

        Random random = new Random();

        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                int randomValue;

                do {
                    // Generate a random number between 1 and MAX (inclusive)
                    randomValue = random.nextInt(MAX) + 1;
                } while (randomValue % 10 != 0 || randomValue % 100 == 0);

                // Assign the generated value to the current element in the grid
                grid[row][col] = randomValue;
            }
        }
    }

    public void printGrid() {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            System.out.println("The grid is empty.");
            return;
        }

        for (int[] row : grid) {
            for (int element : row) {
                System.out.print(element + "\t"); // Separate elements with tabs
            }
            System.out.println(); // Move to the next row
        }
    }

    public static void main(String[] args) {
        int numRows = 3; // Set the number of rows
        int numCols = 4; // Set the number of columns

        Data data = new Data(numRows, numCols);

        // Populate the grid
        data.repopulate();

        // Print the grid
        data.printGrid();
        int increasingCols = data.countIncreasingCols();
        System.out.println("Number of increasing columns: " + increasingCols);
    }
}

Data.main(null)


80	80	90	70	
20	30	50	20	
30	80	60	30	
Number of increasing columns: 0

College Board Answer Key

image.png

image.png

image-2.png

Recap (TAKE NOTES!!!)

In summary, iterating through a 2D array in Java involves using nested loops to visit each element systematically. The outer loop controls the row index, the inner loop controls the column index, and you access and process each element using these indices. Understanding how to iterate through 2D arrays is essential for working with multidimensional data structures in Java.