Search code examples
javaintersection

How to calculate if there is intersection between 2 ranges of ints in Java


I have 2 maximum and minimum values, for example:

22 ------ 26 and 16 ------ 22 (OK, because of 22)
22 ------ 26 and 10 ------ 12 (FAILS)
22 ------ 30 and 29 ------ 33 (OK because of 29 and 30)

I want to know if there exists an intersection between the sets that represent the maximum and minimum, in Java.

I've tried to do it in a paper and got an if with 4 tests, but I found they fail:

if ((thisEntityLeftPosX <= anotherEntityLeftPosX && thisEntityRightPosX >= anotherEntityRightPosX)
            || (thisEntityLeftPosX >= anotherEntityLeftPosX && thisEntityRightPosX >= anotherEntityRightPosX)
            || (thisEntityLeftPosX <= anotherEntityLeftPosX && thisEntityRightPosX <= anotherEntityRightPosX)
            || (thisEntityLeftPosX >= anotherEntityLeftPosX && thisEntityRightPosX >= anotherEntityRightPosX)) {

Maybe there is an easier way.

Not a duplicate because this is not about a number contained in a set, but a set intersection.


Solution

  • Start thinking in the reverse problem: two intervals, that mathematically can be described as [amin, amax] and [bmin, bmax], do not overlap iff (amin > bmax OR bmin > amax).

    So, by simple negation of boolean expressions, these intervals overlap if and only if: (amin <= bmax AND bmin <= amax).