Created
May 26, 2015 02:06
-
-
Save barelyknown/8f71f61cc2392e7cf847 to your computer and use it in GitHub Desktop.
Programming challenge: merging overlapping intervals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class IntervalMerger | |
| def initialize(*intervals) | |
| @intervals = intervals | |
| end | |
| def merge | |
| @intervals.reduce([]) do |merged, i| | |
| is_merged = false | |
| merged.each_with_index do |m, index| | |
| if i[0] <= m[1] && i[1] >= m[0] | |
| merged[index] = [[i,m].map(&:first).min, [i,m].map(&:last).max] | |
| is_merged = true | |
| break | |
| end | |
| end | |
| merged << i unless is_merged | |
| merged | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Easy peasy :)