Merge pull request #15275 from harry9656/task/JAVA-26530

JAVA-26530: Update the RectangleOverlap adding a method without border checks.
This commit is contained in:
Kasra Madadipouya 2023-11-25 14:08:58 +01:00 committed by GitHub
commit 33e3fc580a
2 changed files with 33 additions and 6 deletions

View File

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

View File

@ -1,7 +1,8 @@
package com.baeldung.algorithms.rectanglesoverlap; package com.baeldung.algorithms.rectanglesoverlap;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
public class RectangleUnitTest { public class RectangleUnitTest {
@ -36,4 +37,18 @@ public class RectangleUnitTest {
assertFalse(rectangle1.isOverlapping(rectangle2)); 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));
}
} }