Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number range intersection

Tags:

math

What is the best way to find out whether two number ranges intersect?

My number range is 3023-7430, now I want to test which of the following number ranges intersect with it: <3000, 3000-6000, 6000-8000, 8000-10000, >10000. The answer should be 3000-6000 and 6000-8000.

What's the nice, efficient mathematical way to do this in any programming language?

like image 370
deceze Avatar asked Oct 22 '08 08:10

deceze


People also ask

How do you find the intersection of a range?

An intersection is an interval that lies within all of the given intervals. If no such intersection exists then print -1. [5, 6] is the common interval that lies in all the given intervals. No intersection exists between the two given ranges.

How do you find the intersection of two intervals?

A closed interval [a, b] (with a <= b ) denotes the set of real numbers x with a <= x <= b . The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3] .

How do you find the intersection of two ranges in Java?

To find the actual overlap range, you take the maximum of the two low ends, and the minimum of the two high ends: int e = Math. max(a,b); int f = Math.

How do you find the intersection of two ranges in C++?

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


2 Answers

Just a pseudo code guess:

Set<Range> determineIntersectedRanges(Range range, Set<Range> setofRangesToTest)
{
  Set<Range> results;
  foreach (rangeToTest in setofRangesToTest)
  do
    if (rangeToTest.end <range.start) continue; // skip this one, its below our range
    if (rangeToTest.start >range.end) continue; // skip this one, its above our range
    results.add(rangeToTest);
  done
  return results;
}
like image 67
Chris Kimpton Avatar answered Nov 05 '22 05:11

Chris Kimpton


I would make a Range class and give it a method boolean intersects(Range) . Then you can do a

foreach(Range r : rangeset) { if (range.intersects(r)) res.add(r) }

or, if you use some Java 8 style functional programming for clarity:

rangeset.stream().filter(range::intersects).collect(Collectors.toSet())

The intersection itself is something like

this.start <= other.end && this.end >= other.start
like image 6
Hans-Peter Störr Avatar answered Nov 05 '22 04:11

Hans-Peter Störr