Mountain
Last updated
Last updated
An array of positive integer values has the mountain property if the elements are ordered such that successive values increase until a maximum value (the peak of the mountain) is reached and then the successive values decrease. The Mountain class declaration shown below contains methods that can be used to determine if an array has the mountain property.
You will implement three methods in the Mountain class. For each method, you and your partner will be DRIVER(writing the code) and NAVIGATOR(Offering feedback).
Please decide whom to be the DRIVER or NAVIGATOR.
Complete method isDecreasing(int[] array, int start). The method return true if the mountain decreases continuously from start.
For example,
arr: {1, 2, 3, 2, 1} start: 0
return false, since {1,2,3,2,1} is not decreasing continuously.
arr: {1, 2, 3, 2, 1} start: 2
return true, since {3,2,1} is decreasing continuously.
arr: {1, 2, 3, 3, 1} start: 2
return false, since {3,3,1} is not decreasing continuously.
Mathematically, isDecreasing() returns true if:
for each j such that start<=j<array.length-1, array[j] > array[j+1];
Otherwise return false.
Method IsIncreasing(int[] array, int stop) has been provided for you, which returns true if the mountain increases continuously until the stop. You can refer to it as a hint.
Please change roles now.
Write the Mountain method getPeakIndex. Method getPeakIndex returns the index of the first peak found in the parameter array, if one exists.
A peak is defined as an element whose value is greater than the value of the element immediately before it and is also greater than the value of the element immediately after it.
Method getPeakIndex starts at the beginning of the array and returns the index of the first peak that is found or -1 if no peak is found.
For example, the following table illustrates the results of several calls to getPeakIndex.
Please change roles now.
Write the Mountain method isMountain. Method isMountain returns true if the values in the parameter array are ordered as a mountain; otherwise, it returns false.
The values in array are ordered as a mountain if all three of the following conditions hold.
There must be a peak.
The array elements with an index smaller than the peak’s index must appear in increasing order.
The array elements with an index larger than the peak’s index must appear in decreasing order.
For example, the following table illustrates the results of several calls to isMountain.
You have to call getPeakIndex()
, isIncreasing()
and isDecreasing()
in Part(3) to receive full credit.
Test class has been provided below:
The result should be like: