The Trail problem from the 2010 AP Computer Science Exam is typical of free response problems that test arrays. The problem requires you to find the minimum and maximum in an array and access 2 elements of an array for each loop run.
Review the Trail free response problem with AP CS Tutor Brandon Horn.
Trail Part (a): isLevelTrailSegment
public boolean isLevelTrailSegment(int start, int end)
{
int minElevation = markers[start];
int maxElevation = markers[start];
for (int i = start + 1; i <= end; i++)
{
if (markers[i] < minElevation)
minElevation = markers[i];
if (markers[i] > maxElevation)
maxElevation = markers[i];
}
return maxElevation - minElevation <= 10;
}
Trail Part (b): isDifficult
public boolean isDifficult()
{
int significantChanges = 0;
for (int i = 1; i < markers.length; i++)
if (Math.abs(markers[i - 1] - markers[i]) >= 30)
significantChanges++;
return significantChanges >= 3;
}
2010 AP CS Exam Free Response Solutions |
Recommended Practice Problems |
isnt the int maxElevation = markers[start]; be [end] ?
No. Both the minimum and maximum values can be anything in the array. The first value could be the minimum, the maximum or both.
Since the loop starts at start+1, starting the maximum at the last value would fail if the first value was the maximum. If the loop started at start, it would not matter.
Hi . Why did you start the for loop from (start + 1) ?
minElevation
andmaxElevation
have already been set tomarkers[start]
. Running the loop fori == start
would just comparemarkers[start]
to itself.