Skip to content

Commit b26479a

Browse files
committed
Add Check For Any Overlaps In List Of Ranges as a Ruby til
1 parent 27e1578 commit b26479a

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1178 TILs and counting..._
13+
_1179 TILs and counting..._
1414

1515
---
1616

@@ -905,6 +905,7 @@ _1178 TILs and counting..._
905905
- [Block Comments](ruby/block-comments.md)
906906
- [Build HTTP And HTTPS URLs](ruby/build-http-and-https-urls.md)
907907
- [Chaining Multiple RSpec Change Matchers](ruby/chaining-multiple-rspec-change-matchers.md)
908+
- [Check For Any Overlaps In List Of Ranges](ruby/check-for-any-overlaps-in-list-of-ranges.md)
908909
- [Check If An Object Includes A Module](ruby/check-if-an-object-includes-a-module.md)
909910
- [Check Return Status Of Running A Shell Command](ruby/check-return-status-of-running-a-shell-command.md)
910911
- [Click On Text With Capybara](ruby/click-on-text-with-capybara.md)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)