-3

I'm trying to find the intersection of two ranges in C++? For example, if I have one range as [1..14] inclusive, and another as [10..20] inclusive, I want to get [10..14], as that is the intersection between them.

I found a way on SO as follows :

intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) };
if (intersection.max < intersection.min) {
  intersection.markAsEmpty();
}

I have few variables as follows :

unsigned long long int min1,min2,max1,max2 

for which I'm trying to find the the intersection. Then I did the following:

intersection = { std::max(min1, min2), std::min(max1, max2) };
    if (intersection.max < intersection.min) {
      intersection.markAsEmpty();
    }

But this gives the error that unsigned long long int can't be used. How do I use it find the intersection ?

sammy
  • 75
  • 8
  • How is `intersection` defined? – jpo38 Feb 08 '17 at 20:24
  • Blind "Copy and Pasting" is not good. In the code you copied, `intersection` is an object of a class type that obviously has members `max` and `min`. – WhiZTiM Feb 08 '17 at 20:24
  • Please read http://stackoverflow.com/help/mcve – jpo38 Feb 08 '17 at 20:25
  • 1
    This is not a [mcve]. Please fill in the surrounding class definitions required to fully compile this code. – Xirema Feb 08 '17 at 20:25
  • 2
    Independent of the anyway required [mcve] I would expect that you provide minimum a link when you are talking about someone else code. Just because something is freely available it doesnt mean that you should not mention the original author – 463035818_is_not_an_ai Feb 08 '17 at 20:30

3 Answers3

4

I found a way on SO as follows :

intersection = { std::max(arg1.min, arg2.min), std::min(arg1.max, arg2.max) };
if (intersection.max < intersection.min) {
  intersection.markAsEmpty();
}

Blind "Copy and Pasting" is not good. In the code you copied (which you should acknowledge), intersection is an object of a class type that obviously has members max and min.


For your own use case:

unsigned long long int min1,min2,max1,max2 
......
auto Min = std::max(min1, min2);
auto Max = std::min(max1, max2);
if (Min < Max) {
    // There's an intersection. represented by {Min Max}
}
Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
0

Try this.

#include <algorithm>
#include <utility>

struct range {
    unsigned long long min, max;
};

range intersect(const range& first, const range& second) {
    return {std::max(first.min, second.min), std::min(first.max, second.max)};
}

You can call it like, e.g., intersect({min1, max1}, {min2, max2}).

Sam Marinelli
  • 999
  • 1
  • 6
  • 16
0

may be this will help.

say for the range [l1, r1], [l2, r2] intersection between them can be calculated as:

 if ((r1 < l2) ||  (r2 < l1)) then no intersection exits.

 else l = max(l1, l2) and r = min(r1, r2)

just iterate over the range [l, r] to get the intersection values.

y_159
  • 458
  • 3
  • 15