Search code examples
rubysortingsequences

Split array by consecutive sequences


Given an array of integer such as:

array = [1,2,3,5,6,7,20,21,33,87,88,89,101]

This array contains k consecutive subsequences (in this case k = 6), such as "1,2,3" and "87,88,89". How do I get an array containing arrays of these k subsequences?

For the above example these would be:

[[1,2,3], [5,6,7], [20,21], [33], [87,88,89], [101]]

Solution

  • def seq_sort(array)
      finished = [array.first], i = 0
    
      array.each_cons(2) do |(a,b)|
        if b - a == 1
          finished[i] << b
        else
          finished[i += 1] = [b]
        end
      end
    
      finished
    end
    
    > seq_sort([1,2,38,39,92,94,103,104,105,1002])
    => [[1,2], [38, 39], [92], [94], [103, 104, 105], [1002]]