Array of indexes to array of ranges

前端 未结 7 945
执念已碎
执念已碎 2020-12-09 12:46

Ranges in ruby are pretty cool. I end up with arrays such as this:

geneRanges = [(234..25), (500..510), (1640..1653)]

And subsequently ha

7条回答
  •  -上瘾入骨i
    2020-12-09 13:04

    Functional, not-very-readable solution:

    (a[0,1]+a.each_cons(2).reject{|i,j| j-i==1}.flatten+a[-1,1]).
      each_slice(2).map{|i,j| i..j}
    

    And a nice one:

    class Array
      # splits array to sub-arrays wherever two adjacent elements satisfy a condition
      def split_by
        each_cons(2).inject([[first]]){|a, (i, j)|
          a.push([]) if yield(i, j)
          a.last.push j
          a
        }
      end
    
      # uses split_by to split array to subarrays with consecutive elements, then convert to range
      def to_range
        split_by{|i,j| j-i!=1}.map{|a| a.first..a.last}
      end
    end
    
    [505, 506, 507, 600, 1647, 1648, 1649, 1650, 1651, 1654].split_by{|i,j| j-i!=1}
    #=> [[505, 506, 507], [600], [1647, 1648, 1649, 1650, 1651], [1654]]
    [505, 506, 507, 600, 1647, 1648, 1649, 1650, 1651, 1654].to_range
    #=> [505..507, 600..600, 1647..1651, 1654..1654]
    

提交回复
热议问题