The GrayImage problem from the 2012 AP Computer Science Exam is typical of free response problems that test 2 dimensional arrays.

GrayImage is #4 from the 2012 AP Computer Science A Free Response.

https://secure-media.collegeboard.org/apc/ap_frq_computerscience_12.pdf

Part (a) countWhitePixels method

public int countWhitePixels()
{
    int whitePixels = 0;

    for(int row = 0; row < pixelValues.length; row++)
    {
        for(int col = 0; col < pixelValues[0].length; col++)
        {
            if(pixelValues[row][col] == WHITE)
                whitePixels++;
        }
    }

    return whitePixels;
}

Part (b) processImage method

public void processImage()
{
    for(int row = 0; row < pixelValues.length; row++)
    {
        for(int col = 0; col < pixelValues[0].length; col++)
        {
            int otherRow = row + 2;
            int otherCol = col + 2;

            if(otherRow < pixelValues.length &&
                    otherCol < pixelValues[otherRow].length)
            {
                pixelValues[row][col] -= pixelValues[otherRow][otherCol];
                if(pixelValues[row][col] < BLACK)
                    pixelValues[row][col] = BLACK;
            }
        }
    }
}

Part (b) processImage method (alternate solution)

public void processImage()
{
    for(int row = 0; row < pixelValues.length - 2; row++)
    {
        for(int col = 0; col < pixelValues[0].length - 2; col++)
        {
            pixelValues[row][col] -= pixelValues[row + 2][col + 2];
            if(pixelValues[row][col] < BLACK)
                pixelValues[row][col] = BLACK;
        }
    }
}

2012 AP CS Exam Free Response Solutions

Additional 2D array resources

Comments

Comment on GrayImage