aspose file tools*
The moose likes Programming Diversions and the fly likes Detect Overlapping Rectangles Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Detect Overlapping Rectangles" Watch "Detect Overlapping Rectangles" New topic
Author

Detect Overlapping Rectangles

Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
Here is a problem I ran into at work with some Web development. I came up with a solution, but I am worndering if you can come up with a slicker method.

Given X1,Y1,W1,H1 and X2,Y2,W2,H2 figure out if two rectangles overlap each other.



Eric
Warren Dew
blacksmith
Ranch Hand

Joined: Mar 04, 2004
Posts: 1332
    
    2
If X1+H1 < X2 or X2+H2 < X1 or Y1+W1 < Y2 or Y2+W2 < Y1, they don't overlap (assuming heights and widths are positive). If none of these holds, they overlap. I don't think you can simplify it any further than that.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11419
    
  16

are we assuming the edges are always parallel/perpendicular to the x and y axis?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
Yes for this we are assuming they are parallel/perpendicular.

This is the basic idea I came up with, The first part forces the data to be in the correct orrientation to each other. This is done in JavaScript since that is what I was working with.





Eric
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
Level two:

Detect overlap:



I've heard it takes forever to grow a woman from the ground
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I replaced l and h with a and b respectively, because (1) l is a horrible name for a Java variable, and (2) to me names like l, h, w refer to the total height, length, or width. Since we're using a half-width and half height, I thought it better to remove a possible source of confusion. Anyway:

It might be possible to optimize this a bit more (deferring calculations of y and yMin, until they're really needed) but I think that would lose some clarity.
[ December 31, 2004: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
nicely done
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Detect Overlapping Rectangles