Skip to content

Commit 7339b9d

Browse files
Gopesh111alxkm
andauthored
Add distance between two points algorithm (#7218)
* Add distance between two points algorithm * Create DistanceBetweenTwoPointsTest.java * DistanceBetweenTwoPoints.java * Fix test file package and project structure * Delete src/test/java/com/thealgorithms/DistanceBetweenTwoPointsTest.java * Apply clang-format compliant formatting * Apply clang-format --------- Co-authored-by: a <19151554+alxkm@users.noreply.github.com>
1 parent 109ed2e commit 7339b9d

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* Distance Between Two Points in 2D Space.
5+
*
6+
* <p>This class provides a method to calculate the Euclidean distance between two points in a
7+
* two-dimensional plane.
8+
*
9+
* <p>Formula: d = sqrt((x2 - x1)^2 + (y2 - y1)^2)
10+
*
11+
* <p>Reference: https://en.wikipedia.org/wiki/Euclidean_distance
12+
*/
13+
public final class DistanceBetweenTwoPoints {
14+
15+
private DistanceBetweenTwoPoints() {
16+
// Utility class; prevent instantiation
17+
}
18+
19+
/**
20+
* Calculate the Euclidean distance between two points.
21+
*
22+
* @param x1 x-coordinate of the first point
23+
* @param y1 y-coordinate of the first point
24+
* @param x2 x-coordinate of the second point
25+
* @param y2 y-coordinate of the second point
26+
* @return Euclidean distance between the two points
27+
*/
28+
public static double calculate(final double x1, final double y1, final double x2, final double y2) {
29+
final double deltaX = x2 - x1;
30+
final double deltaY = y2 - y1;
31+
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
32+
}
33+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class DistanceBetweenTwoPointsTest {
8+
9+
@Test
10+
void testDistanceSimple() {
11+
assertEquals(5.0, DistanceBetweenTwoPoints.calculate(0, 0, 3, 4), 1e-9);
12+
}
13+
14+
@Test
15+
void testDistanceNegativeCoordinates() {
16+
assertEquals(5.0, DistanceBetweenTwoPoints.calculate(-1, -1, 2, 3), 1e-9);
17+
}
18+
19+
@Test
20+
void testSamePoint() {
21+
assertEquals(0.0, DistanceBetweenTwoPoints.calculate(2, 2, 2, 2), 1e-9);
22+
}
23+
}

0 commit comments

Comments
 (0)