|
1 | 1 | package com.thealgorithms.misc; |
2 | 2 |
|
3 | | -/* |
4 | | - *A matrix is sparse if many of its coefficients are zero (In general if 2/3rd of matrix elements |
5 | | - *are 0, it is considered as sparse). The interest in sparsity arises because its exploitation can |
6 | | - *lead to enormous computational savings and because many large matrix problems that occur in |
7 | | - *practice are sparse. |
| 3 | +/** |
| 4 | + * Utility class for calculating the sparsity of a matrix. |
| 5 | + * A matrix is considered sparse if a large proportion of its elements are zero. |
| 6 | + * Typically, if more than 2/3 of the elements are zero, the matrix is considered sparse. |
8 | 7 | * |
9 | | - * @author Ojasva Jain |
| 8 | + * Sparsity is defined as: |
| 9 | + * sparsity = (number of zero elements) / (total number of elements) |
| 10 | + * |
| 11 | + * This can lead to significant computational optimizations. |
10 | 12 | */ |
| 13 | +public final class Sparsity { |
11 | 14 |
|
12 | | -final class Sparsity { |
13 | 15 | private Sparsity() { |
14 | 16 | } |
15 | 17 |
|
16 | | - /* |
17 | | - * @param mat the input matrix |
18 | | - * @return Sparsity of matrix |
19 | | - * |
20 | | - * where sparsity = number of zeroes/total elements in matrix |
| 18 | + /** |
| 19 | + * Calculates the sparsity of a given 2D matrix. |
21 | 20 | * |
| 21 | + * @param matrix the input matrix |
| 22 | + * @return the sparsity value between 0 and 1 |
| 23 | + * @throws IllegalArgumentException if the matrix is null, empty, or contains empty rows |
22 | 24 | */ |
23 | | - static double sparsity(double[][] mat) { |
24 | | - if (mat == null || mat.length == 0) { |
| 25 | + public static double sparsity(double[][] matrix) { |
| 26 | + if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { |
25 | 27 | throw new IllegalArgumentException("Matrix cannot be null or empty"); |
26 | 28 | } |
27 | 29 |
|
28 | | - int zero = 0; |
29 | | - // Traversing the matrix to count number of zeroes |
30 | | - for (int i = 0; i < mat.length; i++) { |
31 | | - for (int j = 0; j < mat[i].length; j++) { |
32 | | - if (mat[i][j] == 0) { |
33 | | - zero++; |
| 30 | + int zeroCount = 0; |
| 31 | + int totalElements = 0; |
| 32 | + |
| 33 | + // Count the number of zero elements and total elements |
| 34 | + for (double[] row : matrix) { |
| 35 | + for (double value : row) { |
| 36 | + if (value == 0.0) { |
| 37 | + zeroCount++; |
34 | 38 | } |
| 39 | + totalElements++; |
35 | 40 | } |
36 | 41 | } |
37 | | - // return sparsity |
38 | | - return ((double) zero / (mat.length * mat[0].length)); |
| 42 | + |
| 43 | + // Return sparsity as a double |
| 44 | + return (double) zeroCount / totalElements; |
39 | 45 | } |
40 | 46 | } |
0 commit comments