Ruby, 83 70 60 55 49 characters
f=->a{a.each_cons(3){|x,y,z|p y if(x-y)*(z-y)>0}}
Prints all local extremes to STDOUT.
Uses the <=>
"spaceship" operator, which I really like. (It returns 1 if the first thing is greater than the second, -1 if it's less, and 0 if equal. Therefore, if they add to -2 or 2, that means the middle is an extreme.)
Not anymore, as @daniero pointed out that the "obvious" way is actually shorter!
Changed yet again! Now it uses the awesome algorithm found in MT0's answerMT0's answer (+1 to him!).
Also, I like each_cons
which selects each n
groups of consecutive elements in an array. And trailing if
is interesting too.
Overall, I just like how elegant it looks.
Some sample runs:
irb(main):044:0> f[[1,2,1]]
2
=> nil
irb(main):045:0> f[[1,0,1,0,1]]
0
1
0
=> nil
irb(main):046:0> f[[]]
=> nil
irb(main):047:0> f[[1,2,3,4,5,4,3,2,1]]
5
=> nil
irb(main):048:0> f[[1,1,1,1,1]]
=> nil
irb(main):049:0> f[[10,0,999,-45,3,4]]
0
999
-45
=> nil