ArrayResizer is #4 from the from the 2021 AP Computer Science A Free Response problems.

https://apcentral.collegeboard.org/pdf/ap21-frq-computer-science-a.pdf?course=ap-computer-science-a

Part (a) isNonZeroRow method

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

    return true;
}

Part (a) isNonZeroRow method (alternate)

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

    return true;
}

Row r in array2D is a 1D array. An enhanced for loop can be used to traverse array2D[r]. On the free response, when in doubt, use a regular loop (for or while).

See Enhanced for loop exercises for information on when enhanced for loops are appropriate, and to practice with them.

Part (b) resize method

public static int[][] resize(int[][] array2D)
{
    int[][] newArray = new int[numNonZeroRows(array2D)][array2D[0].length];

    int newR = 0;
    for(int oldR = 0; oldR < array2D.length; oldR++)
    {
        if(isNonZeroRow(array2D, oldR))
        {
            // could copy elements within row instead
            newArray[newR] = array2D[oldR];
            newR++;
        }
    }

    return newArray;
}

See Consolidate an array for an explanation of this algorithm and additional related resources.

The postcondition mentions that array2D must be unchanged. I didn’t see anything in the description or in the examples that prohibited copying references to the existing rows. Although I could see an argument that the contents of each row should be copied into the new array (to prevent later modifications to the returned array from changing the original array), I would argue that the above should receive full credit.

2021 AP CS Exam Free Response Solutions

Additional 2D array resources

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on ArrayResizer