# Split in non-overlapping sub-lists with elements within an interval from the first member

I want to split a large ordered list into consecutive non-overlapping sub-lists, such that all elements are within an interval from the first member of the sub-list . For example:

list={{1,x},{2,x},{3,x},{4,x},{5,x},{8,x},{13,x},{16,x},{17,x}}


And I want to split it so that all first elements are within an interval of 3. The desired result is this:

result={{{1,x},{2,x},{3,x}},{{4,x},{5,x}},{{8,x}},{{13,x}},{{16,x},{17,x}}}


Notice that the interval is relative to the first member of the sub-list and the final result is non-overlapping. So, for example, {{2,x},{3,x},{4,x}} is not in the result.

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign Oct 30, 2020 at 5:05
• Have you tried playing with Partitioni.e. Partition[list, 3] Oct 30, 2020 at 5:05
• Thanks for the suggestion. But yes, I have. The partitioning that I need is not equally spaced and I need this to work with real number values and real-number intervals. The 1,2,3 here is just for illustration.
– Oleg
Oct 30, 2020 at 5:38

Here is a way using SplitBy:

split[l:{__}, m_] :=
Module[{e = l[[1, 1]] + m}
, SplitBy[l, If[#[[1]] < e, e, e = #[[1]] + m]&]
]

split[list, 3]

(* {{{1,x},{2,x},{3,x}},{{4,x},{5,x}},{{8,x}},{{13,x}},{{16,x},{17,x}}} *)

• This works perfectly. Thanks a lot!
– Oleg
Oct 30, 2020 at 8:11

Three variations on WReach's key idea:

ClearAll[splitA]
splitA[l : {__}, m_] := Module[{e = l[[1, 1]] + m},
Last @ Reap @ Scan[Sow[#, If[#[[1]] < e, e,  e = #[[1]] + m]] &, l]]

splitA[list, 3]

 {{{1, x}, {2, x}, {3, x}},
{{4, x}, {5, x}},
{{8, x}},
{{13, x}},
{{16, x}, {17, x}}}

ClearAll[splitB]
splitB[l : {__}, m_] := Module[{e = l[[1, 1]] + m},
Split[l, Or[#2[[1]] < e, e = #2[[1]] + m] &]]

ClearAll[splitC]
splitC[l : {__}, m_] := Module[{e = l[[1, 1]] + m},
SplitBy[l, Or[#[[1]] < e, e = #[[1]] + m] &]]

splitA[list, 3] == splitB[list, 3] == splitC[list, 3]

True

res =
Catenate @ Map[Partition[#, UpTo @ 3] &] @
Split[list, #2[[1]] - #1[[1]] == 1 &];

res == result


(* True *)

list = {{1, x}, {2, x}, {3, x}, {4, x}, {5, x}, {8, x}, {13, x}, {16, x}, {17, x}};


Using SequenceCases:

ConsecutiveQ = Most[#] == Rest[#] - 1 &;

p = Map[Splice@Partition[#, UpTo@3] &];

res = p@SequenceCases[list, x : {__} /; ConsecutiveQ@x[[All, 1]]]

res === result

(*True*)