Skip to content
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 26 additions & 45 deletions src/main/java/com/thealgorithms/misc/Sparsity.java
Original file line number Diff line number Diff line change
@@ -1,56 +1,37 @@
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
*lead to enormous computational savings and because many large matrix problems that occur in
*practice are sparse.
*
* @author Ojasva Jain
*/

final class Sparsity {
private Sparsity() {
final class Sparse {
private Sparse() {
}

/*
* @return Sparsity of matrix
*
* where sparsity = number of zeroes/total elements in matrix
*
*/
static double sparsity(double[][] mat) {
int zero = 0;
// Traversing the matrix to count number of zeroes
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
if (mat[i][j] == 0) {
zero++;
}
}
}
// return sparsity
return ((double) zero / (mat.length * mat[1].length));
static double sparsity(int[][] mat, int rows, int cols, int zero) {
int size = rows * cols;
return (double) zero / size;
}

// 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();
Scanner in = new Scanner(System.in); // Initialize Scanner
try {
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();
int[][] mat = new int[n][m];
int count = 0; // Counter for zeros

System.out.println("Enter Matrix elements: ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
mat[i][j] = in.nextInt();
if (mat[i][j] == 0) {
count++; // Increment zero count directly
}
}
}
}
System.out.println("Sparsity of matrix is: " + sparsity(mat));
in.close();

double sparsityValue = sparsity(mat, n, m, count);
System.out.println("Sparsity of the matrix is: " + sparsityValue);
}
}
}
Loading