Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to partition a sorted array into arrays of contiguous numbers?

Tags:

ruby

Is there an easy way or a method to partition an array into arrays of contiguous numbers in Ruby?

[1,2,3,5,6,8,10] => [[1,2,3],[5,6],[8],[10]]

I can make some routine for that but wonder if there's a quick way.

Sam

like image 737
Sam Kong Avatar asked Dec 19 '22 16:12

Sam Kong


1 Answers

I like to inject:

numbers = [1, 2, 3, 5, 6, 8, 10]
contiguous_arrays = []
contiguous_arrays << numbers[1..-1].inject([numbers.first]) do |contiguous, n|
  if n == contiguous.last.succ
    contiguous << n
  else
    contiguous_arrays << contiguous
    [n]
  end
end

#=> [[1, 2, 3], [5, 6], [8], [10]] 
like image 100
at. Avatar answered May 18 '23 17:05

at.