I have a set of ordered integers, e.g. {1,2,3,6,7,9,10}
and I would like to partition the set in subsets of sequential numbers, e.g. {{1,2,3},{6,7},{9,10}}
. Is there an easy way to do this?
$\begingroup$
$\endgroup$
Add a comment
|
$\begingroup$
$\endgroup$
1
Split[{1, 2, 3, 6, 7, 9, 10}, #2 - #1 == 1 &]
{{1, 2, 3}, {6, 7}, {9, 10}}
-
1$\begingroup$ How come you're using
Chop
here? It works fine without it. $\endgroup$ – Carl Lange Oct 30 '18 at 22:55
$\begingroup$
$\endgroup$
2
Also
FindClusters[{1, 2, 3, 6, 7, 9, 10}]
-
$\begingroup$ FindClusters is O(sqrt n), but split is O(n log n) $\endgroup$ – M.R. Oct 31 '18 at 17:14
-
$\begingroup$ @M.R. Really, thx for the information! I didn't know it. $\endgroup$ – Αλέξανδρος Ζεγγ Oct 31 '18 at 23:54