ArrayResizer free response 2

ArrayResizer free response problem from the 2021 AP Computer Science A Exam.

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 (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;
}

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

2 thoughts on “ArrayResizer free response

  1. Reply Serkan May 15,2021 9:21 am

    Can we copy the elements of array2D to the new array using “for” loops instead of “newArray[newR] = array2D[oldR];”?

    • Reply Brandon Horn May 16,2021 9:47 am

      Yes, you could use a loop through each row to copy the elements from that row into the appropriate row in the new array.

Leave a Reply