|
| 1 | +# Check For Any Overlaps In List Of Ranges |
| 2 | + |
| 3 | +If you have a list of things, such as meetings, you may want to be able to tell |
| 4 | +if there are any conflicts. You could determine that by finding any overlaps in |
| 5 | +their timeslots. |
| 6 | + |
| 7 | +Ranges are a good way to represent any span of data, including a timeslot. |
| 8 | + |
| 9 | +To do this in Ruby, we'll need two pieces. First, a way to determine if two |
| 10 | +`Range` objects are overlapping. Second, an iterative utility for comparing |
| 11 | +each range to every other range. |
| 12 | + |
| 13 | +Here is an `overlaps?` method that uses `Range#begin` and `Range#end`. |
| 14 | + |
| 15 | +```ruby |
| 16 | +def overlaps?(range1, range2) |
| 17 | + range1.begin <= range2.end && range2.begin <= range1.end |
| 18 | +end |
| 19 | +``` |
| 20 | + |
| 21 | +And here is an `any_overlaps?` method to find any overlaps over a list of |
| 22 | +ranges. |
| 23 | + |
| 24 | +```ruby |
| 25 | +def any_overlaps?(ranges) |
| 26 | + ranges.each_with_index do |range1, i| |
| 27 | + ranges.each_with_index do |range2, j| |
| 28 | + return true if i != j && overlaps?(range1, range2) |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + false |
| 33 | +end |
| 34 | + |
| 35 | +puts any_overlaps?([(1..2), (3..4)]) #=> false |
| 36 | +puts any_overlaps?([(1..2), (2..4)]) #=> true |
| 37 | +puts any_overlaps?([(3..4), (1..5)]) #=> true |
| 38 | +``` |
| 39 | + |
| 40 | +This second method isn't optimized, but it will work just fine for small lists |
| 41 | +of ranges. |
| 42 | + |
| 43 | +[source](https://stackoverflow.com/questions/39934266/check-if-two-ranges-overlap-in-ruby) |
0 commit comments