In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
For example, the array arr = [0, 1, 2, 5, 1, 0]
has a peak at position 3
with a value of 5
(since arr[3]
equals 5
).
The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}
.
Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3])
should return {pos: [3, 7], peaks: [6, 3]}
(or equivalent in other languages)
All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
Also, beware of plateaus !!! [1, 2, 2, 2, 1]
has a peak while [1, 2, 2, 2, 3]
and [1, 2, 2, 2, 2]
do not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1])
returns {pos: [1], peaks: [2]}
(or equivalent in other languages)
Have fun!
Didn't made it...
function pickPeaks(arr){
var result = {pos: [], peaks: []};
if(arr.length > 2) {
var pos = -1;
for(var i=1; i<arr.length;i++){
if(arr[i] > arr[i-1]) {
pos = i;
} else if(arr[i] < arr[i-1] && pos != -1) {
result.pos.push(pos);
result.peaks.push(arr[pos]);
pos = -1;
}
}
}
return result;
}
A maximum within a restricted domain, especially a point on a function whose value is greater than the values of all other points near it.
고로 local maxima를 만족하려면
먼저 pos는 -1로 초기화된다.
for문을 통하여 각 배열의 요소가 이전 요소보다 크면 그 값의 인덱스를 pos로 둔다. 이 뜻은 일단 잠재적인 local maxima의 후보로 둔다는 얘기이다.
else if문에서 해당 요소가 이전 요소보다 작고, local maxima의 후보가 존재한다면, 위에서 언급된 1&2번 조건을 다 만족함으로, local maxima가 된다.
result 오브젝트에 해당 인덱스와 값을 추가하고, pos값을 다시 초기화한다.