GrayImage free response answer

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

Review the GrayImage free response solution with AP CS Tutor Brandon Horn.

GrayImage Part (a): countWhitePixels

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

GrayImage Part (b): processImage

  public void processImage()
  {
    for(int row = 0; row < pixelValues.length; row++)
    {
      for(int col = 0; col < pixelValues[row].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;
        }
      }
    }
  }

GrayImage Part (b): processImage – alternate solution

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

Get AP CS Help

2012 AP CS Exam Free Response Solutions