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:
String Initialization in Java
Optional trong Java 8
Phương thức forEach() trong java 8
Giới thiệu luồng vào ra (I/O) trong Java
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Java Program to Implement Counting Sort
Daemon Threads in Java
Intro to Spring Boot Starters
How to Convert List to Map in Java
Entity To DTO Conversion for a Spring REST API
Introduction to Thread Pools in Java
Spring Boot - Admin Server
Registration with Spring Security – Password Encoding
Display Auto-Configuration Report in Spring Boot
So sánh ArrayList và LinkedList trong Java
Guide to the Fork/Join Framework in Java
Java Program to Implement K Way Merge Algorithm
Java Program to Implement Park-Miller Random Number Generation Algorithm
Overflow and Underflow in Java
Migrating from JUnit 4 to JUnit 5
Understanding Memory Leaks in Java
Java Program to Find the Connected Components of an UnDirected Graph
Getting Started with GraphQL and Spring Boot
Hướng dẫn Java Design Pattern – Command
Comparing Objects in Java
An Intro to Spring Cloud Zookeeper
Comparing Long Values in Java
Spring Webflux with Kotlin
Các kiểu dữ liệu trong java
Easy Ways to Write a Java InputStream to an OutputStream
Lập trình đa luồng với CompletableFuture trong Java 8
Java Program to Implement D-ary-Heap