6
$\begingroup$

I want to split a list of positive Integers into sublists whose ascending elements differ by 1.

list = {1, 0, 1, 0, 1, 4, 5, 6, 5, 8, 1, 2};

This can be done easily using Split

Split[list, #2 - #1 == 1 &]

{{1}, {0, 1}, {0, 1}, {4, 5, 6}, {5}, {8}, {1, 2}}

But how can we get the same result

(a) with one of the Sequence-functions (SequenceCases, SequenceSplit or SequencePosition) - or, if this is not possible,

(b) What other options do we have?

$\endgroup$
2
  • $\begingroup$ so differ by one and are ascending? $\endgroup$ Commented Mar 20, 2024 at 11:51
  • 1
    $\begingroup$ yes, exactly, I will specify the question $\endgroup$ Commented Mar 20, 2024 at 11:54

3 Answers 3

4
$\begingroup$

Using SequenceCases with a similar condition like the one for Split:

list = {1, 0, 1, 0, 1, 4, 5, 6, 5, 8, 1, 2};

SequenceCases[list, s_ /; OrderedQ[s, #2 - #1 == 1 &]]

{{1}, {0, 1}, {0, 1}, {4, 5, 6}, {5}, {8}, {1, 2}}

$\endgroup$
5
$\begingroup$
list = {1, 0, 1, 0, 1, 4, 5, 6, 5, 8, 1, 2};

Using SequenceReplace or SequenceCases:

SequenceReplace[list, {b__ /; 
    ContainsOnly[Differences[{b}], {1}]} :> {b}]

Result:

{{1}, {0, 1}, {0, 1}, {4, 5, 6}, {5}, {8}, {1, 2}}

The documentation says:

ContainsOnly[{},list] always returns True

without which this would not be possible.

$\endgroup$
3
$\begingroup$
list = {1, 0, 1, 0, 1, 4, 5, 6, 5, 8, 1, 2};

Using SequenceSplit with the following condition:

SequenceSplit[list, s : {b__ /; MatchQ[Differences[{b}], {1 ...}]} :> s]

{{1}, {0, 1}, {0, 1}, {4, 5, 6}, {5}, {8}, {1, 2}}

$\endgroup$

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.