8
$\begingroup$

Question is very simple. If we have

tst = {2,3,4,6,7,9,11}

result must be

{{2,3,4}, {6,7}, {9}, {11}}

There are similar questions, but not exact.

My best solution is:

myFun[arr_] := Module[{prev = First@arr, tag = First@arr},
Reap[
 Sow[prev, tag];
 Do[
  If[prev != e - 1, tag = e];
  Sow[e, tag];
  prev = e,
  {e, Rest@tst}]
 ]][[2]];

Is it possible to do it better?

$\endgroup$
14
$\begingroup$

Split[] was meant for this:

Split[{2, 3, 4, 6, 7, 9, 11}, #2 - #1 == 1 &]
   {{2, 3, 4}, {6, 7}, {9}, {11}}
$\endgroup$
  • $\begingroup$ #2 - #1 == 1 & I was blind (( Thank you! $\endgroup$ – lesobrod May 22 at 17:19

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.