Question
Program to determine whether a given matrix is a sparse matrix.
A matrix is said to be a sparse matrix if most of the elements of that matrix are 0. It implies that it contains very few non-zero elements.
For the matrix to be sparse, more than half of the elements present in the matrix must be zero.
Enter number of rows in Matrix:4
Enter number of columns in Matrix:3
Enter elements in matrix:
( 1 , 1 ) :1
( 1 , 2 ) :0
( 1 , 3 ) :1
( 2 , 1 ) :1
( 2 , 2 ) :1
( 2 , 3 ) :0
( 3 , 1 ) :0
( 3 , 2 ) :1
( 3 , 3 ) :1
( 4 , 1 ) :0
( 4 , 2 ) :0
( 4 , 3 ) :1
Matrix:
[1 0 1]
[1 1 0]
[0 1 1]
[0 0 1]
Given Matrix is not a Sparse Matrix
Enter number of rows in Matrix:3
Enter number of columns in Matrix:3
Enter elements in matrix:
( 1 , 1 ) :0
( 1 , 2 ) :0
( 1 , 3 ) :1
( 2 , 1 ) :0
( 2 , 2 ) :9
( 2 , 3 ) :0
( 3 , 1 ) :0
( 3 , 2 ) :0
( 3 , 3 ) :0
Matrix:
[0 0 1]
[0 9 0]
[0 0 0]
Given Matrix is Sparse Matrix
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class sparseMatrix
{
public static void main(String[] args)
{
int row=0, col=0,count=0,size=0,i=0,j=0;
int a[][];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE ROW OF MATRIX");
row=sc.nextInt();
System.out.println("ENTER THE COLUMN OF MATRIX");
col=sc.nextInt();
a=new int[row][col];
System.out.println("ENTER THE ELEMENTS IN MATRIX");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
a[i][j]=sc.nextInt();
//counting total number of zeroes
if(a[i][j]==0)
{
count++;
}
}
}
System.out.println("MATRIX:");
for(i=0;i< row;i++)
{
for(j=0;j< col;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
size=row*col;
if(count>(size/2))
{
System.out.println("MATRIX IS A SPARSE MATRIX");
}
else
{
System.out.println("MATRIX IS NOT A SPARSE MATRIX");
}
}
}
Python
import numpy as np
totalNumberOfZeroesInMatrix=0
row=int(input("Enter number of rows in Matrix:"))
column=int(input("Enter number of columns in Matrix:"))
matrix=np.empty([row,column],dtype=np.int)
# Taking input from user
print("Enter elements in matrix:")
for i in range(0,row):
for j in range(0,column):
print("(",(i+1),",",(j+1),")",":",end="")
matrix[i,j]=int(input())
if(matrix[i,j]==0):
totalNumberOfZeroesInMatrix=totalNumberOfZeroesInMatrix+1
#printing the matrix
print("Matrix:")
for i in range(0, row):
print(matrix[i])
# to calculate the total number of elements in given matrix
sizeOfMatrix=row*column
if(totalNumberOfZeroesInMatrix>(sizeOfMatrix//2)):
print("Given Matrix is Sparse Matrix")
else:
print("Given Matrix is not a Sparse Matrix")