Repository: TheAlgorithms/Java
Pull request #5806 (2024-10-14 10:09:34)

feat: Add `KCenters` new algorithm with Junit tests
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5806?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `94.73684%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 64.83%. Comparing base [(`9c76b30`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/9c76b30271535123ea30c0b39a46ccee6b302c6c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`4e10547`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/4e10547f646fdd67fe261afe4623724545c7e09c?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5806?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...a/com/thealgorithms/greedyalgorithms/KCenters.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5806?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fgreedyalgorithms%2FKCenters.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9ncmVlZHlhbGdvcml0aG1zL0tDZW50ZXJzLmphdmE=) | 94.73% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5806?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5806      +/-   ##
============================================
+ Coverage     64.81%   64.83%   +0.02%     
- Complexity     4299     4306       +7     
============================================
  Files           599      600       +1     
  Lines         16764    16783      +19     
  Branches       3219     3225       +6     
============================================
+ Hits          10865    10881      +16     
- Misses         5455     5456       +1     
- Partials        444      446       +2     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5806?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index d2badd76..78ff31bf 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -325,6 +325,7 @@
             * [FractionalKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/FractionalKnapsack.java)
             * [GaleShapley](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/GaleShapley.java)
             * [JobSequencing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/JobSequencing.java)
+            * [KCenters](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java)
             * [MergeIntervals](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MergeIntervals.java)
             * [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimizingLateness.java)
             * [MinimumWaitingTime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTime.java)
@@ -954,6 +955,7 @@
             * [FractionalKnapsackTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/FractionalKnapsackTest.java)
             * [GaleShapleyTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/GaleShapleyTest.java)
             * [JobSequencingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/JobSequencingTest.java)
+            * [KCentersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java)
             * [MergeIntervalsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MergeIntervalsTest.java)
             * [MinimizingLatenessTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimizingLatenessTest.java)
             * [MinimumWaitingTimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/greedyalgorithms/MinimumWaitingTimeTest.java)
diff --git a/src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java b/src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java
new file mode 100644
index 00000000..152b3605
--- /dev/null
+++ b/src/main/java/com/thealgorithms/greedyalgorithms/KCenters.java
@@ -0,0 +1,62 @@
+package com.thealgorithms.greedyalgorithms;
+
+import java.util.Arrays;
+
+/**
+ * Given a set of points and a number k.
+ * The goal is to minimize the maximum distance between any point and its nearest center.
+ * Each point is assigned to the nearest center.
+ * The distance between two points is the Euclidean distance.
+ * The problem is NP-hard.
+ *
+ * @author Hardvan
+ */
+public final class KCenters {
+    private KCenters() {
+    }
+
+    /**
+     * Finds the maximum distance to the nearest center given k centers.
+     * Steps:
+     * 1. Initialize an array {@code selected} of size n and an array {@code maxDist} of size n.
+     * 2. Set the first node as selected and update the maxDist array.
+     * 3. For each center, find the farthest node from the selected centers.
+     * 4. Update the maxDist array.
+     * 5. Return the maximum distance to the nearest center.
+     *
+     * @param distances matrix representing distances between nodes
+     * @param k         the number of centers
+     * @return the maximum distance to the nearest center
+     */
+    public static int findKCenters(int[][] distances, int k) {
+        int n = distances.length;
+        boolean[] selected = new boolean[n];
+        int[] maxDist = new int[n];
+
+        Arrays.fill(maxDist, Integer.MAX_VALUE);
+
+        selected[0] = true;
+        for (int i = 1; i < n; i++) {
+            maxDist[i] = Math.min(maxDist[i], distances[0][i]);
+        }
+
+        for (int centers = 1; centers < k; centers++) {
+            int farthest = -1;
+            for (int i = 0; i < n; i++) {
+                if (!selected[i] && (farthest == -1 || maxDist[i] > maxDist[farthest])) {
+                    farthest = i;
+                }
+            }
+            selected[farthest] = true;
+            for (int i = 0; i < n; i++) {
+                maxDist[i] = Math.min(maxDist[i], distances[farthest][i]);
+            }
+        }
+
+        int result = 0;
+        for (int dist : maxDist) {
+            result = Math.max(result, dist);
+        }
+        return result;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java b/src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java
new file mode 100644
index 00000000..9202d346
--- /dev/null
+++ b/src/test/java/com/thealgorithms/greedyalgorithms/KCentersTest.java
@@ -0,0 +1,15 @@
+package com.thealgorithms.greedyalgorithms;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class KCentersTest {
+
+    @Test
+    public void testFindKCenters() {
+        int[][] distances = {{0, 2, 3, 4}, {2, 0, 5, 1}, {3, 5, 0, 7}, {4, 1, 7, 0}};
+        assertEquals(4, KCenters.findKCenters(distances, 2));
+        assertEquals(2, KCenters.findKCenters(distances, 4));
+    }
+}