Skip to content

Instantly share code, notes, and snippets.

@AdityaBhutani
Last active January 10, 2021 01:35
Show Gist options
  • Save AdityaBhutani/d8f592b7e0f4ed0920fd1cf72f64f756 to your computer and use it in GitHub Desktop.
Save AdityaBhutani/d8f592b7e0f4ed0920fd1cf72f64f756 to your computer and use it in GitHub Desktop.
# Expected arg to be 2-d array and each sub array to have 2 numbers representing range-start and range-end
# [[1, 4], [6, 6], [6, 8], [1, 10]], expected: [[1, 10]]
# program to solve finding the overlapping ranges and combining them.
def range_flatten(arr)
res = []; done = []
arr.each_with_index do |range, i|
a = range.first; b = range.second
arr[(i+1)..-1].each_with_index do |other_range, j|
next if done.include?(i+j+1)
if other_range.first <= b
done << (i+j+1)
first_element = [a, other_range.first].min
second_element = [b, other_range.second].max
res << [first_element, second_element]
break
end
end
if res.size > 1
res_range = res.first
res_other_range = res.second
if res_other_range.first <= res_range.second
first_element = [res_range.first, res_other_range.first].min
second_element = [res_range.second, res_other_range.second].max
res = [[first_element, second_element]]
end
end
end
return res
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment