This questions have asked multiple times and i have seen many threads but my query is very specific. How to see if two rectangles overlap. The test case which finds bug in my code is :
l2 = new RectanglePoint(0, 7);
r2 = new RectanglePoint(6, 10);
l1 = new RectanglePoint(0, 7);
r1 = new RectanglePoint(6, 0);
Function call: isOverlap(new Rectangle(l1, r1), new Rectangle(l2, r2));
My Code:
class RectanglePoint {
int x;
int y;
public RectanglePoint(int x, int y) {
this.x = x;
this.y = y;
}
}
class Rectangle {
RectanglePoint topLeft;
RectanglePoint bottomRight;
public Rectangle(RectanglePoint topLeft, RectanglePoint bottomRight) {
this.topLeft = topLeft;
this.bottomRight = bottomRight;
}
}
public class RectangleOverlap {
public boolean isOverlap(Rectangle rect1, Rectangle rect2) {
return isOverlapHelper1(rect1.topLeft, rect1.bottomRight, rect2.topLeft,
rect2.bottomRight);
}
private boolean isOverlapHelper1(RectanglePoint topLeftA,
RectanglePoint bottomRightA, RectanglePoint topLeftB,
RectanglePoint bottomRightB) {
if (topLeftA.y < bottomRightB.y || topLeftB.y < bottomRightA.y) {
return false;
}
if (topLeftA.x > bottomRightB.x || topLeftB.x > bottomRightA.x) {
return false;
}
return true;
}
The bug is in the condition: if (topLeftA.y < bottomRightB.y || topLeftB.y < bottomRightA.y)
Please help. I already spent lots of time in this.