Skip to content

Commit b510a3c

Browse files
committed
feat: Add KCenters new algorithm with Junit tests
1 parent 9c76b30 commit b510a3c

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Given a set of points and a number k.
7+
* The goal is to minimize the maximum distance between any point and its nearest center.
8+
* Each point is assigned to the nearest center.
9+
* The distance between two points is the Euclidean distance.
10+
* The problem is NP-hard.
11+
*
12+
* @author Hardvan
13+
*/
14+
public final class KCenters {
15+
private KCenters() {
16+
}
17+
18+
/**
19+
* Finds the maximum distance to the nearest center given k centers.
20+
*
21+
* @param distances matrix representing distances between nodes
22+
* @param k the number of centers
23+
* @return the maximum distance to the nearest center
24+
*/
25+
public static int findKCenters(int[][] distances, int k) {
26+
int n = distances.length;
27+
boolean[] selected = new boolean[n];
28+
int[] maxDist = new int[n];
29+
30+
Arrays.fill(maxDist, Integer.MAX_VALUE);
31+
32+
selected[0] = true;
33+
for (int i = 1; i < n; i++) {
34+
maxDist[i] = Math.min(maxDist[i], distances[0][i]);
35+
}
36+
37+
for (int centers = 1; centers < k; centers++) {
38+
int farthest = -1;
39+
for (int i = 0; i < n; i++) {
40+
if (!selected[i] && (farthest == -1 || maxDist[i] > maxDist[farthest])) {
41+
farthest = i;
42+
}
43+
}
44+
selected[farthest] = true;
45+
for (int i = 0; i < n; i++) {
46+
maxDist[i] = Math.min(maxDist[i], distances[farthest][i]);
47+
}
48+
}
49+
50+
int result = 0;
51+
for (int dist : maxDist) {
52+
result = Math.max(result, dist);
53+
}
54+
return result;
55+
}
56+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class KCentersTest {
8+
9+
@Test
10+
public void testFindKCenters() {
11+
int[][] distances = {{0, 2, 3, 4}, {2, 0, 5, 1}, {3, 5, 0, 7}, {4, 1, 7, 0}};
12+
assertEquals(4, KCenters.findKCenters(distances, 2));
13+
assertEquals(2, KCenters.findKCenters(distances, 4));
14+
}
15+
}

0 commit comments

Comments
 (0)