2
$\begingroup$

I have trouble extracting part of a list in a specific order, say, increasingly in a cyclic manner. For example, I have the following list

list={0,10,6,-5,-10}

and I want to extract, as a new list, its increasing values from its minimum to its maximum, but only read in a cyclic manner, i.e. I want it to return {-10, 0, 10}.

Now, I know that in case the list is given already in increasing order, Parts[list,n;;m] does the trick. But for a list with arbitrary order, is there a function that does what I want?

$\endgroup$
  • $\begingroup$ Can you use something like NestWhile[RotateLeft, {0, 10, 6, -5, -10}, First[#] != Min[#] &] as a starting point? $\endgroup$ – J. M.'s technical difficulties May 16 '16 at 18:14
1
$\begingroup$
ClearAll[f]
f = With[{pos = Ordering[#][[{1, -1}]]}, 
     If[Less @@ pos, #[[Span @@ pos]], Join[#[[pos[[1]] ;;]], #[[;; pos[[2]]]]]]] &;

f@{0, 10, 6, -5, -10}

{-10, 0, 10}

f@{0, 10, 6, -10, -5}

{-10, -5, 0, 10}

f@{0, -10, 6, -5, 10}

{-10, 6, -5, 10}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.