2021 AP CSA FRQ 4: ArrayResizer

2021 FRQ #4: ArrayResizer

2D Arrays

9 Points
Timer
25:00

Problem Description

ArrayResizer Class

public class ArrayResizer
{
    /** Returns true if all values in row r are non-zero */
    public static boolean isNonZeroRow(int[][] arr, int r)
    { /* to be implemented in part (a) */ }

    /** Returns a new array with zero-only rows removed */
    public static int[][] resize(int[][] arr)
    { /* to be implemented in part (b) */ }
}

Part A: Check if a row contains all non-zero values

Part B: Create a new array with rows containing any zeros removed

Part A: isNonZeroRow (4 points)

🔓 Solution
public static boolean isNonZeroRow(int[][] arr, int r)
{
    for (int c = 0; c < arr[r].length; c++)
    {
        if (arr[r][c] == 0)
            return false;
    }
    return true;
}

Part B: resize (5 points)

🔓 Solution
public static int[][] resize(int[][] arr)
{
    int nonZeroRows = 0;
    for (int r = 0; r < arr.length; r++)
    {
        if (isNonZeroRow(arr, r))
            nonZeroRows++;
    }
    
    int[][] result = new int[nonZeroRows][arr[0].length];
    int idx = 0;
    for (int r = 0; r < arr.length; r++)
    {
        if (isNonZeroRow(arr, r))
        {
            for (int c = 0; c < arr[0].length; c++)
            {
                result[idx][c] = arr[r][c];
            }
            idx++;
        }
    }
    return result;
}

Related Practice: 2D Arrays

Similar FRQs:

Study Guide:

Daily Practice:

Contact form