Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c compare range intersect

Tags:

objective-c

I am trying to find the intersection of 2 number ranges, say for example...

range A is from 10 to 100, range B is from 60 to 70

Is there an easy way without writing a load of if statements to calculate the intersection of the two ranges, so in this example it would be 10.

Thanks,

like image 268
ChrisM Avatar asked Apr 16 '12 10:04

ChrisM


2 Answers

If you have or make NSRange objects, the NSIntersectionRange function will do this for you. Just be sure to check what it returns when there is no intersection.

NSRange a = NSMakeRange(10, 90);
NSRange b = NSMakeRange(60, 10);
NSRange intersection = NSIntersectionRange(a, b);
if (intersection.length <= 0)
    NSLog(@"Ranges do not intersect");
else
    NSLog(@"Intersection = %@", NSStringFromRange(intersection));
like image 136
Cowirrie Avatar answered Nov 04 '22 09:11

Cowirrie


You can use this method for that purpose:

NSRange NSIntersectionRange (
   NSRange range1,
   NSRange range2
);

You can find all the info here:

NSIntersectionRange Apple Doc

like image 38
Antonio MG Avatar answered Nov 04 '22 09:11

Antonio MG