Mathematica 66 58 51
Current Solution
Shortened thanks to a contribution by Calle.
Cases[Partition[#,3,1],{a_,b_,c_}/;(a-b) (b-c)<0⧴b]&
Partition[#,3,1]
finds the triples.
(a-b) (b-c)<0
is true if and only if b
is below a
, c
, or above a
,c
.
and looks at takes the signs of the differences. A local extreme will return either {-1,1}
or {1,-1}
.
Examples
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{1, 2, 1}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{0, 1, 0, 1, 0}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{}]
Cases[Partition[#, 3, 1], {a_, b_, c_} /; (a - b) (b - c) < 0 :> b] &[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]
{2}
{1, 0, 1}
{}
{10, 6, 9, 0, 1}
Earlier Solution
This looks examples all triples (generated by Partition
) and determines whether the middle element is less than both extremes or greater than the extremes.
Cases[Partition[#,3,1],{a_,b_,c_}/;(b<a∧b<c)∨(b>a∧b>c)⧴b]& ;
First Solution
This finds the triples, and looks at takes the signs of the differences. A local extreme will return either {-1,1}
or {1,-1}
.
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}⧴x[[2]]]&
Example
Cases[Partition[#,3,1],x_/;Sort@Sign@Differences@x=={-1,1}:>x[[2]]]&[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]
{10, 6, 9, 0, 1}
Analysis:
Partition[{9, 10, 7, 6, 9, 0, 3, 3, 1, 10}]
{{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3,
3}, {3, 3, 1}, {3, 1, 10}}
%
refers to the result from the respective preceding line.
Differences/@ %
{{1, -3}, {-3, -1}, {-1, 3}, {3, -9}, {-9, 3}, {3, 0}, {0, -2}, {-2, 9}}
Sort@Sign@Differences@x=={-1,1}
identifies the triples from {{9, 10, 7}, {10, 7, 6}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {0, 3, 3}, {3, 3, 1}, {3, 1, 10}} such that the sign (-, 0, +) of the differences consists of a -1
and a 1
. In the present case those are:
{{9, 10, 7}, {7, 6, 9}, {6, 9, 0}, {9, 0, 3}, {3, 1, 10}}
For each of these cases, x, x[[2]]
refers to the second term. Those will be all of the local maxima and minima.
{10, 6, 9, 0, 1}
1 2 2 1
shouldn't those2
be considered as extremes too? - I know, this would make the solution much more difficult... \$\endgroup\$