Skip to content

Commit a6aadd5

Browse files
refactor: improve Sparsity class with input validation and clearer logic (TheAlgorithms#6351)
Co-authored-by: Deniz Altunkapan <[email protected]>
1 parent c997a32 commit a6aadd5

File tree

1 file changed

+28
-22
lines changed

1 file changed

+28
-22
lines changed
Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,46 @@
11
package com.thealgorithms.misc;
22

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.
87
*
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.
1012
*/
13+
public final class Sparsity {
1114

12-
final class Sparsity {
1315
private Sparsity() {
1416
}
1517

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.
2120
*
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
2224
*/
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) {
2527
throw new IllegalArgumentException("Matrix cannot be null or empty");
2628
}
2729

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++;
3438
}
39+
totalElements++;
3540
}
3641
}
37-
// return sparsity
38-
return ((double) zero / (mat.length * mat[0].length));
42+
43+
// Return sparsity as a double
44+
return (double) zeroCount / totalElements;
3945
}
4046
}

0 commit comments

Comments
 (0)