5
$\begingroup$

I have a list with some entries being sequential and some not. I would like to construct a list of lists split by sequential entries. In this context, sequential means the integer value increases by 1.

Please note that in some cases, there are more than two sequential elements (only up to 3 in this example but in practice could be more).

I thought that some combination of Sow/Reap would work but couldn't figure out how to use those.

countByPosition = {1, 2, 1, 2, 1, 2, 62, 63, 1, 2, 1, 2, 1, 2, 64, 65, 191, 192, 193, \
1, 2, 191, 192, 193, 1, 2, 191, 192, 193, 1, 2, 191, 192, 193, 1, 2, \
191, 192, 193, 1, 2, 191, 192, 193, 1, 2, 191, 192, 1, 2, 191, 192, \
1, 2, 191, 192, 1, 2, 191, 192, 1, 2, 191, 192, 1, 2, 191, 192};

I have an extremely crude way of generating what I want and am hoping for a more elegant solution.

resultList = {};
subList = {countByPosition[[1]]};
lastEntry = countByPosition[[1]];
For[i = 2, i <= Length[countByPosition], i++,
 If[
   countByPosition[[i]] - lastEntry == 1,
   AppendTo[subList, countByPosition[[i]]];
   lastEntry = countByPosition[[i]];
   ,
   AppendTo[resultList, subList];
   subList = {countByPosition[[i]]};
   lastEntry = countByPosition[[i]];
   ];
 ];

resultList
(* {{1, 2}, {1, 2}, {1, 2}, {62, 63}, {1, 2}, {1, 2}, {1, 2}, {64, 
  65}, {191, 192, 193}, {1, 2}, {191, 192, 193}, {1, 2}, {191, 192, 
  193}, {1, 2}, {191, 192, 193}, {1, 2}, {191, 192, 193}, {1, 
  2}, {191, 192, 193}, {1, 2}, {191, 192}, {1, 2}, {191, 192}, {1, 
  2}, {191, 192}, {1, 2}, {191, 192}, {1, 2}, {191, 192}, {1, 2}} *)

All suggestions appreciated.

$\endgroup$

1 Answer 1

13
$\begingroup$
Split[countByPosition, #2 == # + 1 &]

enter image description here

$\endgroup$
1
  • 3
    $\begingroup$ Elegant, as always. $\endgroup$ Nov 29, 2021 at 21:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.