8
$\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$ Commented Jul 1, 2023 at 14:31
  • $\begingroup$ @user1066 I suppose you mean the first example or two under Generalizations & Extensions $\endgroup$
    – Michael E2
    Commented Jul 1, 2023 at 15:33

4 Answers 4

12
$\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
  • 2
    $\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
    Commented Jul 2, 2023 at 1:23
11
$\begingroup$

Using SequenceSplit:

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

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

Found a solution by myself:

SequenceCases[ls, {__}?OrderedQ]

Wonder if there's a neater one :)

$\endgroup$
1
$\begingroup$
list = {2, 3, 1, 2, 3, 3, 2, 1};

Using SequenceCases

SequenceCases[list, x_ /; LessEqual @@ x]

Using SequenceSplit (new in 11.3)

SequenceSplit[list, x_ /; LessEqual @@ x :> x]

Both produce

{{2, 3}, {1, 2, 3, 3}, {2}, {1}}

$\endgroup$

Your Answer

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

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