I have a list of randomly ordered unique closed-end ranges R0...Rn-1 where
Ri = [r1i, r2i] (r1i <= r2i)
Subsequently some of the ranges overlap (partially or completely) and hence require merging.
My question is, what are the best-of-breed algorithms or techniques used for merging such ranges. Examples of such algorithms or links to libraries that perform such a merging operation would be great.
What you need to do is:
Sort items lexicographically where range key is [r_start,r_end]
Iterate the sorted list and check if current item overlaps with next. If it does extend current item to be r[i].start,r[i+1].end, and goto next item. If it doesn't overlap add current to result list and move to next item.
Here is sample code:
vector<pair<int, int> > ranges; vector<pair<int, int> > result; sort(ranges.begin(),ranges.end()); vector<pair<int, int> >::iterator it = ranges.begin(); pair<int,int> current = *(it)++; while (it != ranges.end()){ if (current.second > it->first){ // you might want to change it to >= current.second = std::max(current.second, it->second); } else { result.push_back(current); current = *(it); } it++; } result.push_back(current);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With