diff --git a/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPoints.java b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPoints.java new file mode 100644 index 0000000000..92ec3272c1 --- /dev/null +++ b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPoints.java @@ -0,0 +1,16 @@ +package com.baeldung.math.pointbetweentwopoints; + +public class PointLiesBetweenTwoPoints { + public static boolean findUsingDistanceFormula(double x1, double y1, double x2, double y2, double x, double y) { + double distanceAC = Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)); + double distanceCB = Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2)); + double distanceAB = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); + return Math.abs(distanceAC + distanceCB - distanceAB) < 1e-9; + } + + public static boolean findUsingSlopeFormula(double x1, double y1, double x2, double y2, double x, double y) { + double slopeAB = (y2 - y1) / (x2 - x1); + double slopeAC = (y - y1) / (x - x1); + return slopeAB == slopeAC && ((x1 <= x && x <= x2) || (x2 <= x && x <= x1)) && ((y1 <= y && y <= y2) || (y2 <= y && y <= y1)); + } +} diff --git a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPointsUnitTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPointsUnitTest.java new file mode 100644 index 0000000000..e41d0c1d05 --- /dev/null +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/pointbetweentwopoints/PointLiesBetweenTwoPointsUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.math.pointbetweentwopoints; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PointLiesBetweenTwoPointsUnitTest { + + @Test + public void givenAPoint_whenUsingDistanceFormula_thenCheckItLiesBetweenTwoPoints() { + double x1 = 1, y1 = 1; + double x2 = 5, y2 = 5; + double x = 3, y = 3; + assertTrue(PointLiesBetweenTwoPoints.findUsingDistanceFormula(x1, y1, x2, y2, x, y)); + } + + @Test + public void givenAPoint_whenUsingSlopeFormula_thenCheckItLiesBetweenTwoPoints() { + double x1 = 1, y1 = 1; + double x2 = 5, y2 = 5; + double x = 3, y = 3; + assertTrue(PointLiesBetweenTwoPoints.findUsingSlopeFormula(x1, y1, x2, y2, x, y)); + } +}