Skip to main content
1 of 3
algorithmshark
  • 8.8k
  • 2
  • 33
  • 55

J - 22 char

Couldn't help it ;)

(}.@}:#~0=2+/\2*@-/\])

Explanation follows:

  • 2*@-/\] - Over each pair of elements in the argument (each 2-item long infix) take the signum of the difference. This is equal to 1 if the difference is positive, 0 if zero, and -1 if negative.
  • 2+/\ - Now over each of these new pairs, add the elements.
  • 0= - Test whether each result is equal to 0. This only happens if 1 is added to -1, i.e. if one side had a positive difference and the other had a negative.
  • }.@}: - Cut off the first and the last element, because those can't possibly be extrema, and we lost information for them anyway by doing the pairs stuff above.
  • #~ - Use the true values on the right side to pick items from the list on the left side.

Usage:

   (}.@}:#~0=2+/\2*@-/\]) 1 2 1
2
   (}.@}:#~0=2+/\2*@-/\]) 0 1 0 1 0
1 0 1
   (}.@}:#~0=2+/\2*@-/\]) i.0   NB. i.0 is the empty list (empty result also)

   (}.@}:#~0=2+/\2*@-/\]) 0 1 2 0 1 0
2 0 1
algorithmshark
  • 8.8k
  • 2
  • 33
  • 55