10

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?

Rohit Namjoshi
  • 10,212
  • 6
  • 16
  • 67
lesobrod
  • 1,657
  • 9
  • 14

1 Answers1

14

Split[] was meant for this:

Split[{2, 3, 4, 6, 7, 9, 11}, #2 - #1 == 1 &]
   {{2, 3, 4}, {6, 7}, {9}, {11}}
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574