Skip to content

Commit 92ff833

Browse files
committed
add null checker in algorithm
1 parent bb66f17 commit 92ff833

2 files changed

Lines changed: 9 additions & 5 deletions

File tree

src/main/java/com/thealgorithms/randomized/ClosestPair.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,13 @@ public static Object[] rabinRandomizedClosestPair(List<Point> points) {
7676
}
7777
}
7878

79+
// Confirm neither closestA nor closestB are null
80+
if (closestA == null || closestB == null) {
81+
closestA = points.get(0);
82+
closestB = points.get(1);
83+
delta = euclideanDistance(closestA, closestB);
84+
}
85+
7986
// Create a grid, We will use "Probabilistic Filtering" by only checking
8087
// neighboring grids to prevent bruteforce checking outside initialization
8188
Map<String, Point> grid = new HashMap<>();

src/test/java/com/thealgorithms/randomized/ClosestPairTest.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,8 @@ void testStandardCaseClosestPair() {
2323
void testTwoDistinctPoints() {
2424
List<Point> points = Arrays.asList(new Point(1, 2), new Point(2, 3));
2525
Object[] closestPair = ClosestPair.rabinRandomizedClosestPair(points);
26-
27-
// Add null check for closestPair
28-
assertNotNull(closestPair, "Closest pair result should not be null");
29-
assertTrue((closestPair[0].equals(points.get(0)) && closestPair[1].equals(points.get(1))) || (closestPair[1].equals(points.get(0)) && closestPair[0].equals(points.get(1))), "The closest pair should include the given distinct points");
30-
assertEquals(closestPair[2], ClosestPair.euclideanDistance(points.get(0), points.get(1)), "The calculated distance should match the Euclidean distance");
26+
assertTrue((closestPair[0].equals(points.get(0)) && closestPair[1].equals(points.get(1))) || (closestPair[1].equals(points.get(0)) && closestPair[0].equals(points.get(1))));
27+
assertEquals(closestPair[2], ClosestPair.euclideanDistance(points.get(0), points.get(1)));
3128
}
3229

3330
@Test

0 commit comments

Comments
 (0)