I have found the solution but wanted to ensure my logic is the most efficient. I feel that there is a better way. I have the (x,y) coordinate of the bottom left corner, height and width of 2 rectangles, and i need to return a third rectangle that is their intersection. I do not want to post the code as i feel it is cheating.
- I figure out which is furthest left and highest on the graph.
- I check if one completely overlaps the other, and reverse to see if the other completely overlaps the first on the X axis.
- I check for partial intersection on the X axis.
- I basically repeat steps 2 and 3 for the Y axis.
- I do some math and get the points of the rectangle based on those conditions.
I may be over thinking this and writing inefficient code. I already turned in a working program but would like to find the best way for my own knowledge. If someone could either agree or point me in the right direction, that would be great!
You can also use the Rectangle source code to compare with your own algorithm:
The accepted answer is incorrect. Here's my version, which is correct.
Do not use the accepted answer.
Why not use JDK API to do this for you?
To use
java.awt.Rectangle
class, the parameters of the constructor are: x, y, width, height, in which x, y are the top-left corner of the rectangle. You can easily convert the bottom-left point to top-left.I recommend the above, but if you really want to do it yourself, you can follow the steps below:
say
(x1, y1), (x2, y2)
are bottom-left and bottom-right corners of Rect1 respectively,(x3, y3), (x4, y4)
are those of Rect2.x1
,x3
and the smaller one ofx2
,x4
, sayxL
,xR
respectivelyxL >= xR
, then return no intersection elsey1
,y3
and the smaller one ofy2
,y4
, sayyT
,yB
respectivelyyT >= yB
, then return no intersection else(xL, yB, xR-xL, yB-yT)
.A more Java-like pseudo code:
As you see, if your rectangle was originally defined by two diagonal corners, it will be easier, you only need to do the
// find intersection
part.