How many peaks in my mountain range?
CJam (32 26 24 21 bytes)
0q~0]e`1f=2ew::>2,/,(
Expected input is space-separated numbers.
Online demo ; full test suite (expected output is a 1
per test case).
Thanks to Martin for informing me that the current version of CJam improves one of the operators used, saving 2 chars; and for a further 3-char saving.
Dissection
Two phases: deduplicate, then identify local maxima in each set of three.
0q~0] e# Put the input in an array wrapped in [0 ... 0]
e`1f= e# Use run-length encoding to deduplicate
2ew::> e# Map [a b c ...] to [(a>b) (b>c) ...]
2,/ e# Split on [0 1], which since we've deduplicated occurs when (a<b) (b>c)
,( e# Count the parts and decrement to give the number of [0 1]s
JavaScript (ES6), 54 51 bytes
m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h
Explanation
Takes an array of numbers
m=>
m.map(n=>{ // for each number n in the mountain range
h=
n<p? // if the number is less than the previous number:
h&& // if the previous number was greater than the number before it
!++r // increment the number of peaks and set h to 0
:n>p||h; // if the number is greater than the previous number, set h to 1
p=n // set p to the current number
},
r= // r = number of peaks
h= // h = 1 if the previous number was higher than the one before it
p=0 // p = previous number
)|r+h // return the output (+ 1 if the last number was higher)
Test
var solution = m=>m.map(n=>{h=n<p?h&&!++r:n>p||h;p=n},r=h=p=0)|r+h
Mountain Range (space-separated) = <input type="text" id="input" value="87 356 37673 3676 386 909 909 909 909 454 909 908 909" />
<button onclick="result.textContent=solution(input.value.split(' ').map(n=>+n))">Go</button>
<pre id="result"></pre>
Pyth, 25 23 bytes
L._M-M.:b2s<R0y-y+Z+QZZ
Explanation:
L y = lambda b:
._M -M .: signs of subsets
b of b
2 of length 2. That is, signs of differences.
s <R number of elements less than
0 0 in
y - y of ... with zeroes removed
y + y of
Z the input with zeroes tacked on both sides
+ Q Z
Z