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

后端 未结 5 2191
-上瘾入骨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:19

    Another approach

    def summarize(x)
      x.inject([]) do |acc, value|
        if acc.last && acc.last[1] + 1 == value
          acc.last[1] = value
          acc
        else
          acc << [value,value]
        end
      end
    end
    

    Similar to Larsenal's method but using inject to manage the boring stuff.

提交回复
热议问题