Detecting overlapping ranges in Ruby

前端 未结 4 1226
孤街浪徒
孤街浪徒 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

    Consider this:

    class Range
      include Comparable
    
      def <=>(other)
        self.begin <=> other.begin
      end
    
      def self.overlap?(*ranges)
        edges = ranges.sort.flat_map { |range| [range.begin, range.end] }
        edges != edges.sort.uniq
      end
    end
    
    Range.overlap?(2..12, 6..36, 42..96) # => true
    

    Notes:

    1. This could take in any number of ranges.
    2. Have a look at the gist with some tests to play with the code.
    3. The code creates a flat array with the start and end of each range.
    4. This array will retain the order if they don't overlap. (Its easier to visualize with some examples than textually explaining why, try it).

提交回复
热议问题