Determine if two rectangles intersect without case logic

Assuming you have two rectangles A and B that exist parallel to the x and y axis and are defined by their upper left (x1,x2) and lower right corners (x2,y2). How can you calculate if A and B intersect without using case logic?

A = { (x1,y1), (x2,y2) }
B = { (x1,y1), (x2,y2) }

 

intersect

 

The answer is:

if (A.x1 < B.x2 && 
    A.x2 > B.x1 &&  
    A.y1 < B.y2 && 
    A.y2 > B.y1) {
  then A and B intersect
}

There is a great analysis here:

http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other

And an awesome interactive visualization by Matthew Crumley here:

https://silentmatt.com/rectangle-intersection/

Advertisements