DEV Community

Riches
Riches

Posted on

Pick peaks"Code Wars"

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 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!

Steps:

  1. let create a response variable that will hold the structure of our response.
  2. let create a loop which will start from 1 and end at the index before the last one. this is because of the condition given in the question.
  3. let create a variable and initiate it to 1. this will be used to determine the value of the next index.
  4. let us have a while loop which will be used to check if the value of current number is equal to the next. if so then no peak so move to the next value.
  5. finally we have a loop which will enable us get the peak position once the condition are met. Once we get them we put it to the response variable.
  6. we return the response.

Image description

Algorithm.

function pickPeaks(arr) {
    const response = { pos: [], peaks: [] };

    for (let i = 1; i < arr.length - 1; i++) {

        let next = 1;
        while (arr[i] === arr[i + next]) next++;

        if (arr[i] > arr[i - 1] && arr[i] > arr[i + next]) {
            response.pos.push(i);
            response.peaks.push(arr[i]);
        };
    };

    return response;
}

console.log(pickPeaks([1, 2, 5, 4, 3, 2, 3, 6, 4, 1, 2, 3, 3, 4, 5, 3, 2, 1, 2, 3, 5, 5, 4, 3]));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)