A list of positive integers can be visualized as a quantized mountain range where each list entry represents the height of one vertical section of the mountains.
For example, the list
1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3
can become the range
x
x x
xxxxx xxx x
xxxxxxxx xxxxxx x
xxxxxxxxxxxxxxxxxx
(Less poetic people might call this a bar chart, but I digress.)
The question in this challenge is: How many peaks are in the mountain range of some arbitrary list? Essentially, how many local maxima are in the list?
A peak is defined as a contiguous section of one or more columns of the mountain range that are all equal in height, where the columns immediately to the left and the right are lower in height.
It's easy to visually tell that the example has four peaks at these parenthesized locations:
1, 2, 2, 3, (4), 3, (5), 3, 2, 1, 2, (3, 3, 3), 2, 2, 1, (3)
Note how the (3, 3, 3)
plateau section counts as a peak because it is a contiguous set of columns equal in height, higher than its neighboring columns.
The last (3)
counts as a peak as well because, for the purposes of this challenge, we'll define the left neighbor of the leftmost column and the right neighbor of the rightmost column to both be height zero.
This means that a list with only one value, for example 1, 1, 1
, can be interpreted as 0, 1, 1, 1, 0
, and thus has one peak, not none: 0, (1, 1, 1), 0
.
The only list with zero peaks is the empty list.
Challenge
Write a function or program that takes in an arbitrary list of positive integers and prints or returns the number of peaks in the corresponding mountain range.
The shortest code in bytes wins. Tiebreaker is earlier post.
Test Cases
Input List -> Output Peak Count
[empty list] -> 0
1, 1, 1 -> 1
1, 2, 2, 3, 4, 3, 5, 3, 2, 1, 2, 3, 3, 3, 2, 2, 1, 3 -> 4
1 -> 1
1, 1 -> 1
2, 2, 2, 2, 2 -> 1
90 -> 1
2, 1, 2 -> 2
5, 2, 5, 2, 5 -> 3
2, 5, 2, 5, 2, 5, 2 -> 3
1, 2, 3, 4 -> 1
1, 2, 3, 4, 1, 2 -> 2
1, 3, 5, 3, 1 -> 1
7, 4, 2, 1, 2, 3, 7 -> 2
7, 4, 2, 1, 2, 1, 2, 3, 7 -> 3
1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10
1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1 -> 10
2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 -> 10
1, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 3, 3, 3, 1 -> 4
12, 1, 2, 1, 2, 3, 3, 3, 2, 4, 4, 4, 1, 5, 5, 4, 7, 9 -> 6
87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 909 -> 3
87, 356, 37673, 3676, 386, 909, 909, 909, 909, 454, 909, 908, 909 -> 4