Question 4: 2D Array
Counting peaks on a height map
- Units 2 and 4
- 6 points
- About 22 minutes
You write one method that traverses, analyzes or changes data in a 2D array, often of objects, using the classes described in the question. New since the course was revised for 2025–26 (first tested in May 2026): it's worth 6 points instead of 9, and points are no longer taken off as penalties. On the exam: Question 4 of 4, 6 points. Section II has 4 free-response questions in 90 minutes (45% of the score), all assessing Practice 2 (Develop Code). The exam is fully digital in Bluebook: you type your Java, and the Java Quick Reference is provided. No calculator. Suggested time is our split of the 90 minutes by points; College Board gives no per-question timing.
The question and its sources
A hiking app models a region as a grid of heights. The Terrain class stores the heights, in meters, in a two-dimensional array of int values. When an element of a two-dimensional array is accessed, the first index is the row and the second index is the column.
The Terrain class
public class Terrain
{
/**
* The height of each square of the region. heights has at least
* one row and at least one column, and every row has the same length.
*/
private int[][] heights;
/**
* Returns the number of peaks in heights, as described in the question.
* Postcondition: heights is unchanged.
*/
public int countPeaks()
{ /* to be implemented */ }
// There may be instance variables, constructors, and methods that are not shown.
}Example: heights
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 | 4 | 2 | 2 |
| 1 | 3 | 2 | 6 | 1 |
| 2 | 5 | 1 | 3 | 7 |
Source: Hypothetical example
Suggested time: 22 minutes
Your answers are saved in this browser as you type.
Part (a)
6 pointsA square's *neighbors* are the squares directly above, below, left and right of it that are inside the grid. A square on an edge or in a corner has fewer than four neighbors. A square is a *peak* if its height is strictly greater than the height of every one of its neighbors.
Write the Terrain method countPeaks, which returns the number of peaks.
In the example above, there are 4 peaks: the 4 at row 0, column 1; the 6 at row 1, column 2; the 5 at row 2, column 0; and the 7 at row 2, column 3. The 2 at row 0, column 3 is not a peak, because its neighbor to the left is also 2.
Complete method countPeaks.public int countPeaks()
Tab indents. Press Esc, then Tab, to move on.
0 lines · 0 / 2,500 characters
Checking scoring…
Scoring it yourself shows you the rubric, examples and a model answer. Try writing your answer first.