|
Re: boolean
|
Posted: Apr 7, 2006 12:54 AM
|
|
Do they have to overlap exactly or do you want to get the region where they overlap?
You could just use the equals method of a rectangle in the first case.
return rectangle1.equals(rectangle2)
If that doesn't work for any reason just compare every parameter of rectangle.
return rectangle1.x == rectangle2.x && rectangle1.y == rectangle2.y && rectangle1.width == rectangle2.width && rectangle1.height == rectangle2.height;
2nd case: get the overlapping region. 1. Test, if there IS an overlapping region 1.1 rectangle2.x must not be bigger than rectangle1.x+rectangle1.width 1.2 rectangle1.x must not be bigger than rectangle2.x+rectangle2.width 1.3 rectangle2.y must not be bigger than rectangle1.y+rectangle1.height 1.4 rectangle1.x must not be bigger than rectangle2.y+rectangle2.height
2. find maxX, maxY, double maxX = Math.max(rectangle1.x, rectangle2.x); double maxY = Math.max(rectangle1.y, rectangle2.y);
double minX2 = Math.min(rectangle1.x + rectangle1.width, rectangle2.x + rectangle2.width); double minY2 = Math.min(rectangle1.y + rectangle1.height, rectangle2.y + rectangle1.height); double newWidth = minX2 - maxX; double newWidth = minY2 - maxY;
new Rectangle(maxX, maxY, newWidth, newHeight);
Note: You can skip the test if you just check if newWidth or newHeight are negative. In that case return null.
Since I think that you have SOME knowledge about Java (or should get it doing this exercise), it shouldn't be much of a problem to put this in a class and to write the methods.
For your solution with just one coordinate post here your math code in pseudo-code (basic-like if you want). I can help you translate it to java. But I can assure you that the classic way is faster. I used 4 compare operations and 3 logical operations. If the x-value is different, it will only be one compare operation and maybe (don't know exactly how it's implemented) one logical operation.
|
|