6
$\begingroup$

I would like to split a list into non-overlapping, ascending (more precisely, non-descending with ≤) sublists. The function would be close to LongestOrderedSequence, but instead of the longest one, we want all the ordered sequences. An example:

ls = {2, 3, 1, 2, 3, 3, 2, 1};

split[ls] == {{2, 3}, {1, 2, 3, 3}, {2}, {1}}
$\endgroup$
2
  • $\begingroup$ @user1066 Perfect — that should be an answer! Why did I presume that sequence-related functions should start with Sequence :) $\endgroup$ Jul 1 at 14:31
  • $\begingroup$ @user1066 I suppose you mean the first example or two under Generalizations & Extensions $\endgroup$
    – Michael E2
    Jul 1 at 15:33

3 Answers 3

10
$\begingroup$

I think this must be a duplicate, but as the answer below is (almost) identical to an example in Split, I have tagged it Community Wiki and posted what was originally a comment as an answer.

ls = {2, 3, 1, 2, 3, 3, 2, 1};

Split[ls, LessEqual]

(* {{2, 3}, {1, 2, 3, 3}, {2}, {1}} *) 
$\endgroup$
1
  • 1
    $\begingroup$ That this is not in the lead makes me think active site users no longer have the ability to discern quality. $\endgroup$
    – Michael E2
    Jul 2 at 1:23
10
$\begingroup$

Using SequenceSplit:

SequenceSplit[ls, {x_, y___}?OrderedQ :> {x, y}]

(*{{2, 3}, {1, 2, 3, 3}, {2}, {1}}*)
$\endgroup$
7
$\begingroup$

Found a solution by myself:

SequenceCases[ls, {__}?OrderedQ]

Wonder if there's a neater one :)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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