I am working on an algorithm problem to try to determine whether two rectangles overlap with each other.
Assume L1
and R1
are the top-left and bottom-right of the first rectangle, and L2
and R2
as the top left and bottom-right of the second rectangle.
I determined that it was easier to first determine when the rectangles don't overlap, and here are my rules:
L2.x >= R1.x // rectangle 2 is right of rectangle 1
R2.x <= L1.x // rectangle 2 is left of rectangle 1
R2.y <= L1.y // rectangle 2 is top of rectangle 1
L2.y >= R1.y // rectangle 2 is bottom of rectangle 1
So put together, we take the not
of this, which means whenever the conditions for not overlapping are satisfied, then the rectangles are overlapping.
public static boolean isOverlap(L1, R1, L2, R2) {
if(!(L2.x >= R1.x) || !(R2.x <= L1.x) || !(R2.y <= L1.y) || !(L2.y >= R1.y)) {
return true;
}
return false;
}
I feel like I'm not doing this correctly. While I drew everything out on a piece of paper to solve this problem, I feel like I am missing something. What did I do wrong?
Test Cases:
// Rectangle 2 is two x-units away from Rectangle 1
// Should not overlap
Point L1 = new Point(0, 0);
Point R1 = new Point(2, 2);
Point L2 = new Point(4, 0);
Point R2 = new Point(6, 2);
if(isOverlap(L1, R1, L2, R2)) {
System.out.println("Overlapping");
} else {
System.out.println("Not overlapping");
}
Output:
Overlapping
Looking at this answer, I am quite close, but it seems I flipped the top/bottom conditions: http://www.geeksforgeeks.org/find-two-rectangles-overlap/