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:
Spring WebFlux Filters
Java Program to Implement Bucket Sort
Introduction to PCollections
Giới thiệu Java 8
Java Byte Array to InputStream
Hashtable trong java
Spring Boot - Bootstrapping
Quick Guide to the Java StringTokenizer
Java NIO2 Path API
Java Program to Solve Tower of Hanoi Problem using Stacks
The Dining Philosophers Problem in Java
Hướng dẫn kết nối cơ sở dữ liệu với Java JDBC
Guava Collections Cookbook
Quick Guide to Spring MVC with Velocity
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
JUnit 5 @Test Annotation
REST Web service: Basic Authentication trong Jersey 2.x
An Example of Load Balancing with Zuul and Eureka
Java Program to Implement Ternary Search Tree
Jackson – Decide What Fields Get Serialized/Deserialized
Apache Camel with Spring Boot
Jackson Annotation Examples
Java Program to Implement Merge Sort Algorithm on Linked List
Copy a List to Another List in Java
Examine the internal DNS cache
Hướng dẫn Java Design Pattern – Decorator
Java Program to Implement Interval Tree
Java Program to Implement Sorted Singly Linked List
Java Program to Check if a Given Binary Tree is an AVL Tree or Not
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Introduction to Liquibase Rollback
Java Program to Evaluate an Expression using Stacks