Learn AP Comp Sci

Problem of the Day

Problem:

The static method convert is designed to use a one-dimensional Array of positive integers for filling a two-dimensional Array of the same integers arranged into a specified number of rows and columns, and returning that result. If there are insufficient values in the one-dimensional array to fill the two-D array, values of -1 are placed in the extra locations. If there are too many values in the one-dimensional array to fit into the specified two-dimensional array, those extra values are left out of the two-dimensional result.

A partial listing of the method is given here.

/**
* Converts a 1-dimensional Array to a 2-dimensional with the
* given number of rows and cols. If the 1-D Array is not large
* enough to fill the 2-d Array, values of -1 are used for the
* extra values. If the 1-dimensional Array is to large to fit
* into the specified 2-D Array, the extra values are left out.
* @param arr a 1-D integer Array
* @param rows the number of rows in the 2-d Array to be returned
* @param cols the number of cols in the 2-d Array to be returned
* PRECONDITION: rows and cols >= 1
*/
public static int[][] convert(int[] arr, int rows, int cols)
{
int[][] result = new int[rows][cols];

/* missing code */

return result;
}

Which of the following can be used to replace /* missing code */ so that the method will work as described?


  1. int i = 0;
    for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
    if (i < arr.length)
    {
    result[r][c] = arr[i];
    i++;
    }
    else
    {
    result[r][c] = -1;
    }
    }
    }

  2. int i = 0;
    for (int r = 0; r < rows; r++) {
    for (int c = 0; c < cols; c++) {
    if (i < rows * cols)
    {
    result[r][c] = arr[i];
    i++;
    }
    else
    {
    result[r][c] = -1;
    }
    }
    }

  3. int r = 0;
    int c = 0;
    int i = 0;
    while (i < rows * cols) {
    if (i < arr.length)
    result[r][c] = arr[i];
    else
    result[r][c] = -1;
    i += 1;
    r = i / cols;
    c = i % cols;
    }
    return result;
  1. I only
  2. II only
  3. III only
  4. I and II only
  5. I and III only

Show solution:

The correct answer is e. In option I, nested-for loops work through the rows and columns while the index i works its way through the one-dimensional Array. In option III, the index variable i keeps counting until the two-dimensional Array is filled, with row and column indexes being manipulated manually using integer division and modulo operations to identify the correct row and column based on i.