A simple algorithm to find whether a set of ranges overlap.
Notes:
- This could take in any number of ranges.
- Have a look at the gist with some tests to play with the code.
- The code creates a flat array with the start and end of each range.
- This array will retain the order if they don't overlap. (Its easier to visualize with some examples than textually explaining why, try it).
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
[
[true, [2..12, 6..36, 42..96]],
].each do |result, ranges|
Test.assert_equals result, Range.overlap?(*ranges)
end