[ISSUE] Rectangle overlap tutorial is either wrong or the problem statement is wrong
DamnedElric opened this issue · comments
Article and Module Links
Tutorial: https://www.baeldung.com/java-check-if-two-rectangles-overlap
Describe the Issue
The tutorial does not define whether "touching" rectangles are considered to be overlapping or not. I would argue that in order for there to be overlap, at least one point needs to be inside the other rectangle.
To Reproduce
Failing testcase:
@Test
public void givenTwoTouchingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(5, 0), new Point(17, 14));
Rectangle rectangle2 = new Rectangle(new Point(0, 0), new Point(5, 14));
assertFalse(rectangle1.isOverlapping(rectangle2));
}
Expected Behavior
Either the article should be updated to explain that touching rectangles are considered to be overlapping (which I think is wrong), or the algorithm should be updated to take touching into account (which I'd prefer). This is pretty simple: the bounds checks should simply be made inclusive:
public boolean isOverlapping(Rectangle other) {
// one rectangle is to the top of the other
if (this.topRight.getY() <= other.bottomLeft.getY() || this.bottomLeft.getY() >= other.topRight.getY()) {
return false;
}
// one rectangle is to the left of the other
if (this.topRight.getX() <= other.bottomLeft.getX() || this.bottomLeft.getX() >= other.topRight.getX()) {
return false;
}
return true;
}
Additional Context
I realise that not many people are likely to care about this. I only came across this issue because I'm tutoring a student who had trouble with a similar assignment and ended up copying the Baeldung solution.
Hey, @DamnedElric, thanks for the feedback.
This issue will remain open while we look into this.
Well, it really depends on the definition here imho and the point of view. But It's a good point to update the article in order to explicit this.
also
In physics, I guess you cannot state that two objects that are in the same exact spot, are not overlapping.
While practically speaking you can imagine two objects touching but not overlapping, you might imagine that this never really occurs.
but yeah, again, I think we should explicit better in the article
Hi @DamnedElric - we adjusted the code and the article to reflect both solutions, considering two rectangles touch if their borders overlap or not.