JAVA-26530: Update the RectangleOverlap adding a method without borders check.

This commit is contained in:
Harry9656 2023-11-23 06:21:19 +01:00
parent e97806ca52
commit 79e9818bee
2 changed files with 33 additions and 6 deletions

View File

@ -26,13 +26,25 @@ public class Rectangle {
this.topRight = topRight;
}
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()) {
public boolean isOverlapping(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() < comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() > comparedRectangle.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()) {
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() < comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() > comparedRectangle.topRight.getX()) {
return false;
}
return true;
}
public boolean isOverlappingWithoutBorders(Rectangle comparedRectangle) {
// one rectangle is to the top of the comparedRectangle
if (this.topRight.getY() <= comparedRectangle.bottomLeft.getY() || this.bottomLeft.getY() >= comparedRectangle.topRight.getY()) {
return false;
}
// one rectangle is to the left of the comparedRectangle
if (this.topRight.getX() <= comparedRectangle.bottomLeft.getX() || this.bottomLeft.getX() >= comparedRectangle.topRight.getX()) {
return false;
}
return true;

View File

@ -1,7 +1,8 @@
package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class RectangleUnitTest {
@ -36,4 +37,18 @@ public class RectangleUnitTest {
assertFalse(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingCalled_shouldReturnTrue() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertTrue(rectangle1.isOverlapping(rectangle2));
}
@Test
public void givenAdjacentRectangles_whensOverlappingWithoutBordersCalled_shouldReturnFalse() {
Rectangle rectangle1 = new Rectangle(new Point(0, 0), new Point(5, 14));
Rectangle rectangle2 = new Rectangle(new Point(5, 0), new Point(17, 14));
assertFalse(rectangle1.isOverlappingWithoutBorders(rectangle2));
}
}