How do I summarize array of integers as an array of ranges?

后端 未结 5 2178
-上瘾入骨i
-上瘾入骨i 2020-12-16 02:48

I\'d like to take input such as:

[1,2,4,5,6,7,9,13]

and turn it into something like the following:

[[1,2],[4,7],[9,9],[13,1         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 03:12

    An even easier solution than @tokland's very nice one is using chunk_while:

    xs.chunk_while { |a, b| a + 1 == b }.map do |seq|
      [seq.first, seq.last]
    end
    

    Note: chunk_while was introduced in Ruby 2.3

提交回复
热议问题