Detecting overlapping ranges in Ruby

前端 未结 4 1230
孤街浪徒
孤街浪徒 2021-01-03 06:50

I have array of ranges :

[[39600..82800], [39600..70200],[70200..80480]]

I need to determine if there is overlapping or not.What is an easy

4条回答
  •  被撕碎了的回忆
    2021-01-03 07:22

    For sake of simplicity and readability I'll suggest this approach:

    def overlaps?(ranges)
      ranges.each_with_index do |range, index|
        (index..ranges.size).each do |i|
          nextRange = ranges[i] unless index == i
          if nextRange and  range.to_a & nextRange.to_a 
            puts "#{range} overlaps with #{nextRange}"
          end
        end
      end
    end
    
    
    r = [(39600..82800), (39600..70200),(70200..80480)]
    overlaps?(r)
    

    and the output:

    ruby ranges.rb 
    39600..82800 overlaps with 39600..70200
    39600..82800 overlaps with 70200..80480
    39600..70200 overlaps with 70200..80480
    

提交回复
热议问题