Skip to content

Instantly share code, notes, and snippets.

@nevans
Created August 26, 2010 01:39
Show Gist options
  • Save nevans/550622 to your computer and use it in GitHub Desktop.
Save nevans/550622 to your computer and use it in GitHub Desktop.
Collapse an array of ranges into the union of their ranges
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