Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mythicalprogrammer/5849755 to your computer and use it in GitHub Desktop.
Save mythicalprogrammer/5849755 to your computer and use it in GitHub Desktop.
set1 = [[1,2],[5,7],[9,12]] set2 = [[3,4],[5,6],[13,17]] Merge the two set of interval Interview question, where the answer should be: [[1, 7], [9, 17]] There probably a corner case I'm missing somewhere. It's too early in the morning to think wah.
set1 = [[1,2],[5,7],[9,12]]
set2 = [[3,4],[5,6],[13,17]]
puts set1.inspect
puts set2.inspect
puts "combind the two set"
set3 = set1 + set2
puts set3.inspect
puts "sort by lower bound"
set3 = set3.sort
puts set3.inspect
puts "merge lower bound"
def lower_bound_merge(data,pos,acc)
if pos == (data.length)
acc
else
if acc.empty?
if data[pos-1][1]+1 == data[pos][0]
acc << [data[pos-1][0],data[pos][1]]
end
lower_bound_merge(data,pos+1,acc)
else
last_acc = (acc.length-1)
if acc[last_acc][1]+1 == data[pos][0]
acc << [acc[last_acc][0],data[pos][1]]
acc.delete_at((last_acc))
else
acc << data[pos]
end
lower_bound_merge(data,pos+1,acc)
end
end
end
#lower_bound_merge(set3,1,set4)
set4 = lower_bound_merge(set3,1,Array.new())
puts set4.inspect
puts "lower bound within range merge"
def lower_bound_within_merge(data,pos,acc)
if pos == (data.length)
acc
else
if acc.empty?
if data[pos][0] < data[pos-1][1]
acc << [data[pos-1][0],data[pos][1]]
end
lower_bound_within_merge(data,pos+1,acc)
else
last_acc = (acc.length-1)
if data[pos][0] < acc[last_acc][1]
acc << [acc[last_acc][0],data[pos][1]]
acc.delete_at((last_acc))
else
acc << data[pos]
end
lower_bound_within_merge(data,pos+1,acc)
end
end
end
set4 = lower_bound_within_merge(set4,1,Array.new())
puts set4.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment