This is the java program to find out a given matrix is sparse matrix or not. Sparse matrix contains zero elements above a certain threshold. This threshold is given by (n*m)/2, where n and m are the rows and columns in matrix. Hence, if a matrix contains more than nm/2 mumber of zeros it is sparse matrix otherwise not.
Here is the source code of the Java Program to Check if it is a Sparse Matrix. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
//This is a sample program to check whether the matrix is sparse matrix or not
//The complexity of the code is O(n^2)
import java.util.Scanner;
public class Sparsity_Matrix
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the dimensions of the matrix: ");
int m = sc.nextInt();
int n = sc.nextInt();
double[][] mat = new double[m][n];
int zeros = 0;
System.out.println("Enter the elements of the matrix: ");
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
mat[i][j] = sc.nextDouble();
if(mat[i][j] == 0)
{
zeros++;
}
}
}
if(zeros > (m*n)/2)
{
System.out.println("The matrix is a sparse matrix");
}
else
{
System.out.println("The matrix is not a sparse matrix");
}
sc.close();
}
}
Output:
$ javac Sparsity_matrix.java $ java Sparsity_matrix Enter the dimensions of the matrix: 2 3 Enter the elements of the matrix: 1 0 0 2 1 1 The matrix is not a sparse matrix $ javac Sparsity_matrix.java $ java Sparsity_matrix Enter the dimensions of the matrix: 3 4 Enter the elements of the matrix: 1 0 0 0 0 1 0 0 0 0 1 1 The matrix is a sparse matrix
Related posts:
Mapping a Dynamic JSON Object with Jackson
Migrating from JUnit 4 to JUnit 5
Assertions in JUnit 4 and JUnit 5
Java Program to Represent Graph Using Adjacency List
Converting a Stack Trace to a String in Java
Spring Security Form Login
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement Binary Search Tree
Wrapper Classes in Java
Simple Single Sign-On with Spring Security OAuth2
A Guide to JPA with Spring
Spring Data MongoDB – Indexes, Annotations and Converters
Spring WebFlux Filters
Từ khóa this và super trong Java
Hướng dẫn Java Design Pattern – Facade
Java Program to Implement Bellman-Ford Algorithm
Java Program to Implement Meldable Heap
A Guide to Spring Cloud Netflix – Hystrix
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Collection trong java
Java Program to Implement Heap
Spring Boot - Sending Email
Spring Boot - Zuul Proxy Server and Routing
Java equals() and hashCode() Contracts
Java Program to Perform Searching in a 2-Dimension K-D Tree
Spring Boot - Runners
Java Program to Implement Ford–Fulkerson Algorithm
An Intro to Spring Cloud Vault
Java – Reader to InputStream
Creating a Custom Starter with Spring Boot
Java Program to Construct an Expression Tree for an Postfix Expression
Java Program to Implement Sorted Circular Doubly Linked List