7
$\begingroup$

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?

$\endgroup$
9
$\begingroup$
Split[{1, 2, 3, 6, 7, 9, 10}, #2 - #1 == 1 &]  

{{1, 2, 3}, {6, 7}, {9, 10}}

$\endgroup$
  • 1
    $\begingroup$ How come you're using Chop here? It works fine without it. $\endgroup$ – Carl Lange Oct 30 '18 at 22:55
7
$\begingroup$

Also

FindClusters[{1, 2, 3, 6, 7, 9, 10}]
$\endgroup$
  • $\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

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.