2012 Gray Image

<< 2012 HorseBarn | APQuestionsTrailIndex | 2011 Sound >>

Click here to see the questions from 2012


public class GrayImage
	public static final int BLACK=0;
	public static final int WHITE=255;

	 * The 2-dimensional representation of this image. Guaranteed not to be null. 
	 * All values in the array are within the range [BLACK, WHITE], inclusive. 
	private int[][] pixelValues;

	/** @return the total number of white pixels in this image. 
	 * Postcondition: this image has not been changed.
	public int countWhitePixels()
		/* to be implemented in part (a) */ 
		return -1;

	/** Processes this image in row-major order and decreases the value of each pixel at
	 * position (row, col) by the value of the pixel at position (row + 2, col + 2) if it exists.
	 * Resulting values that would be less than BLACK are replaced by BLACK.
	 * Pixels for which there is no pixel at position (row + 2, col + 2) are unchanged. */

	public void processImage()
		/* to be implemented in part (b) */ 
	public GrayImage(int[][] p)
	public String toString(){
		int rows=pixelValues.length;
		int cols=pixelValues[0].length;
		String[] s=new String[rows];
		for(int r=0;r<rows;r++){
			s[r]=String.format(" %2d",r);
			for (int c=0; c<cols;c++)
		String result="  ";
		for (int c=0;c<cols;c++)
			result+=String.format("%5d", c);
		for (int r=0;r<rows;r++)
		return result;


public class GrayImageTester 
	public static void main (String[] args)
		int [][] p={{255,184,178,84,129},{84,255,255,130,84},{78,255,0,0,78},{84,130,255,130,84}};
		int [][] p2={{221,184,178,84,135},{84,255,255,130,84},{78,255,0,0,78},{84,130,255,130,84}};
		int [][] p3={{221,184,100,84,135},{0,125,171,130,84},{78,255,0,0,78},{84,130,255,130,84}};
		GrayImage pic=new GrayImage(p);
		GrayImage pic2=new GrayImage(p2);
		GrayImage pic3=new GrayImage(p3);
		System.out.println("Part A");
		System.out.println(pic+"\ncountWhitePixels() should return 5");
		System.out.println("your code returns "+pic.countWhitePixels());
		System.out.println("Part B");
		System.out.println("processImage() should change \n"+pic2+"\n into \n"+pic3);
		System.out.println("your code produces\n"+pic2);