6
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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 $\endgroup$ – Dunlop Oct 30 at 5:05
  • 1
    $\begingroup$ Have you tried playing with Partitioni.e. Partition[list, 3] $\endgroup$ – Dunlop Oct 30 at 5:05
  • $\begingroup$ 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. $\endgroup$ – Oleg Oct 30 at 5:38
7
$\begingroup$

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}}} *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ This works perfectly. Thanks a lot! $\endgroup$ – Oleg Oct 30 at 8:11
2
$\begingroup$

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
| 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.