Repository: TheAlgorithms/Java
Pull request #5780 (2024-10-13 14:25:47)

Add tests, remove `main`, fix bug in `Sparsity`
<!--
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`

alxkm: @Hardvan to merge this, update issues should be resolved
Hardvan: @alxkm I have resolved the merge conflict.

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 398f61ec..652ecbfd 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -1033,6 +1033,7 @@
             * [PalindromePrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java)
             * [PalindromeSinglyLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/PalindromeSinglyLinkedListTest.java)
             * [RangeInSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java)
+            * [SparsityTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/SparsityTest.java)
             * [ThreeSumProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java)
             * [TwoSumProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java)
             * [WordBoggleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/WordBoggleTest.java)
diff --git a/src/main/java/com/thealgorithms/misc/Sparsity.java b/src/main/java/com/thealgorithms/misc/Sparsity.java
index cae2fbde..08e50a12 100644
--- a/src/main/java/com/thealgorithms/misc/Sparsity.java
+++ b/src/main/java/com/thealgorithms/misc/Sparsity.java
@@ -1,7 +1,5 @@
 package com.thealgorithms.misc;
 
-import java.util.Scanner;
-
 /*
  *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements
  *are 0, it is considered as sparse). The interest in sparsity arises because its exploitation can
@@ -16,12 +14,17 @@ final class Sparsity {
     }
 
     /*
+     * @param mat the input matrix
      * @return Sparsity of matrix
      *
      * where sparsity = number of zeroes/total elements in matrix
      *
      */
     static double sparsity(double[][] mat) {
+        if (mat == null || mat.length == 0) {
+            throw new IllegalArgumentException("Matrix cannot be null or empty");
+        }
+
         int zero = 0;
         // Traversing the matrix to count number of zeroes
         for (int i = 0; i < mat.length; i++) {
@@ -32,25 +35,6 @@ final class Sparsity {
             }
         }
         // return sparsity
-        return ((double) zero / (mat.length * mat[1].length));
-    }
-
-    // Driver method
-    public static void main(String[] args) {
-        Scanner in = new Scanner(System.in);
-        System.out.println("Enter number of rows in matrix: ");
-        int n = in.nextInt();
-        System.out.println("Enter number of Columns in matrix: ");
-        int m = in.nextInt();
-
-        System.out.println("Enter Matrix elements: ");
-        double[][] mat = new double[n][m];
-        for (int i = 0; i < n; i++) {
-            for (int j = 0; j < m; j++) {
-                mat[i][j] = in.nextDouble();
-            }
-        }
-        System.out.println("Sparsity of matrix is: " + sparsity(mat));
-        in.close();
+        return ((double) zero / (mat.length * mat[0].length));
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/misc/SparsityTest.java b/src/test/java/com/thealgorithms/misc/SparsityTest.java
new file mode 100644
index 00000000..b93e4f44
--- /dev/null
+++ b/src/test/java/com/thealgorithms/misc/SparsityTest.java
@@ -0,0 +1,36 @@
+package com.thealgorithms.misc;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class SparsityTest {
+
+    private static final double DELTA = 1e-9;
+
+    @ParameterizedTest(name = "Test case {index}: {2}")
+    @MethodSource("provideTestCases")
+    public void testSparsity(double[][] matrix, double expectedSparsity, String description) {
+        assertEquals(expectedSparsity, Sparsity.sparsity(matrix), DELTA, description);
+    }
+
+    private static Stream<Arguments> provideTestCases() {
+        return Stream.of(Arguments.of(new double[][] {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}, 1.0, "Matrix with all zero elements"), Arguments.of(new double[][] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, 0.0, "Matrix with no zero elements"),
+            Arguments.of(new double[][] {{0, 2, 0}, {4, 0, 6}, {0, 8, 0}}, 5.0 / 9.0, "Matrix with mixed elements"), Arguments.of(new double[][] {{0, 1, 0, 2, 0}}, 3.0 / 5.0, "Single-row matrix"), Arguments.of(new double[][] {{1}, {0}, {0}, {2}}, 2.0 / 4.0, "Single-column matrix"),
+            Arguments.of(new double[][] {{0}}, 1.0, "Matrix with a single zero element"), Arguments.of(new double[][] {{5}}, 0.0, "Matrix with a single non-zero element"));
+    }
+
+    @ParameterizedTest(name = "Test case {index}: {1}")
+    @MethodSource("provideExceptionTestCases")
+    public void testSparsityExceptions(double[][] matrix, String description) {
+        assertThrows(IllegalArgumentException.class, () -> Sparsity.sparsity(matrix), description);
+    }
+
+    private static Stream<Arguments> provideExceptionTestCases() {
+        return Stream.of(Arguments.of(new double[][] {}, "Empty matrix should throw IllegalArgumentException"));
+    }
+}