Check if a point lies between 2 points (#15554)

Co-authored-by: rajatgarg <rajatgarg@adobe.com>
This commit is contained in:
Rajat Garg 2024-01-06 03:59:56 +05:30 committed by GitHub
parent 20c3c8e7cc
commit d3e944a159
2 changed files with 39 additions and 0 deletions

View File

@ -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));
}
}

View File

@ -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));
}
}