Created
August 26, 2010 01:39
-
-
Save nevans/550622 to your computer and use it in GitHub Desktop.
Collapse an array of ranges into the union of their ranges
This file contains 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
def collapse_array_of_ranges(array) | |
# simplify, by sorting on range.begin | |
array.sort_by(&:begin).inject([]) do |a, r| | |
# compared with last range... | |
last_range = a[-1] | |
if last_range && last_range.include?(r.begin) | |
# ignore range if it is completely inside of last range | |
unless(last_range.include?(r.end)) | |
# this range overlaps last range, | |
# thus, pull off last range and merge them | |
a.pop | |
a.push(last_range.begin..r.end) | |
end | |
else | |
# this range does not intersect last range | |
# thus, put it on array | |
a.push(r) | |
end | |
a | |
end | |
end | |
collapse_array_of_ranges([1..3, 2..4, 2..7]) | |
# => [1..7] | |
collapse_array_of_ranges([1..3, 2..4, 2..7, 8..9]) | |
# => [1..7, 8..9] | |
collapse_array_of_ranges([805..827, 326..426, 1..10, 526..715, 708..722, 804..826]) | |
# => [1..10, 326..426, 526..722, 804..827] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment