Skip to content

Commit c59d125

Browse files
authored
Add Sparcity of a Matrix [Hacktoberfest] (TheAlgorithms#2659)
1 parent d7ccd2f commit c59d125

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Misc/Sparcity.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package Misc;
2+
import java.util.*;
3+
/*
4+
*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).
5+
*The interest in sparsity arises because its exploitation can lead to enormous computational savings and because many large matrix problems that occur in practice are sparse.
6+
*
7+
* @author Ojasva Jain
8+
*/
9+
10+
class Sparcity{
11+
/*
12+
* @return Sparcity of matrix
13+
*
14+
* where sparcity = number of zeroes/total elements in matrix
15+
*
16+
*/
17+
static double sparcity(double [][] mat){
18+
int zero =0;
19+
//Traversing the matrix to count number of zeroes
20+
for(int i=0;i<mat.length;i++){
21+
for(int j=0;j<mat[i].length;j++){
22+
if(mat[i][j]==0)
23+
zero++;
24+
}
25+
}
26+
//return sparcity
27+
return ((double)zero/(mat.length*mat[1].length));
28+
}
29+
30+
//Driver method
31+
public static void main(String [] args){
32+
Scanner in = new Scanner(System.in);
33+
System.out.println("Enter number of rows in matrix: ");
34+
int n = in.nextInt();
35+
System.out.println("Enter number of Columns in matrix: ");
36+
int m = in.nextInt();
37+
38+
System.out.println("Enter Matrix elements: ");
39+
double [][] mat = new double[n][m];
40+
for(int i=0;i<n;i++){
41+
for(int j=0;j<m;j++){
42+
mat[i][j] = in.nextDouble();
43+
}
44+
}
45+
System.out.println("Sparcity of matrix is: "+ sparcity(mat));
46+
}
47+
}

0 commit comments

Comments
 (0)