A hiking trail has elevation markers posted at regular intervals along the trail. Elevation information about a trail can be stored in an array, where each element in the array represents the elevation at a marker. The elevation at the first marker will be stored at array index 0, the elevation at the second marker will be stored at array index 1, and so forth. Elevations between markers are ignored in this question. The graph below shows an example of trail elevations.

Part A

Write a function isLevelTrailSegment whose function header is written in pseudocode as follows:

FUNCTION isLevelTrailSegment(trail:ARRAY[1:n] OF INTEGER, startIndex:INTEGER, endIndex:INTEGER) RETURNS BOOLEAN

A trail segment is defined by a starting marker, an ending marker, and all markers between those two markers. The parameters of the function are the array of trail elevation markers, the index of the starting marker and the index of the ending marker.

The method will return TRUE if the difference between the maximum elevation and the minimum elevation in the trail segment is less than or equal to 10 meters, and FALSE otherwise

For the trail array shown at the beginning of the question, the trail segment starting at marker 4 and ending at marker 7 has elevations ranging between 121 and 129 meters. Because the difference between 121 and 129 is less than or equal to 10, the trail segment is considered level.

The trail segment starting at marker 0 and ending at marker 3 has elevations ranging between 90 and 140 meters. Because the difference between 90 and 140 is greater than 10, this trail segment is not considered level.

Part B

Write a function isDifficult whose function header is written in pseudocode as follows:

FUNCTION isDifficult(trail:ARRAY[1:n] OF INTEGER) RETURNS BOOLEAN

A trail is rated by counting the number of changes in elevation that are at least 30 meters (up or down) between two consecutive markers. A trail with 3 or more such changes is rated difficult. The following table shows trail elevation data and the elevation changes between consecutive trail markers.

This trail is rated difficult because it has 4 changes in elevation that are 30 meters or more (between markers 0 and 1, between markers 1 and 2, between markers 3 and 4, and between markers 5 and 6).

Video Solutions

Remember, these solutions are here to support you. Make sure you attempt each question first.

Also, make sure you talk to your teacher or classmates if any of the solutions don't make sense!

Part A

Part B