Skip to content

2D Arrays Part 1 HW #9

@eshaank1

Description

@eshaank1

2021 FRQ:

Part A.

public static boolean isNonZeroRow(int[][] array2D, int r) {
    for (int value : array2D[r]) {
        if (value == 0) {
            return false;
        }
    }
    return true;
}

Loops through all elements in the specified row r.
If any element is 0, the method returns false.
If the loop completes without finding a 0, the method returns true.

Part B.

public static int[][] resize(int[][] array2D) {
    int numRows = numNonZeroRows(array2D); // Get the number of non-zero rows
    int[][] result = new int[numRows][]; // Create a new 2D array with the correct size

    int index = 0;
    for (int i = 0; i < array2D.length; i++) {
        if (isNonZeroRow(array2D, i)) {
            result[index] = array2D[i]; // Add the non-zero row to the result
            index++;
        }
    }

    return result;
}

First determines how many rows contain only non-zero elements using numNonZeroRows.
Initializes a new 2D array (result) with the appropriate number of rows.
Iterates through each row of the input array. For every row that satisfies isNonZeroRow, it adds that row to the result array.

Explanation of errors:

  • The method numNonZeroRows was not defined in the code until I added it later

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions