একটি স্পার্স ম্যাট্রিক্স হল একটি ম্যাট্রিক্স যার বেশিরভাগ উপাদান 0। এর জন্য একটি উদাহরণ নিম্নরূপ দেওয়া হল।
নিচের ম্যাট্রিক্সে ৫টি শূন্য রয়েছে। যেহেতু শূন্যের সংখ্যা ম্যাট্রিক্সের উপাদানের অর্ধেকেরও বেশি তাই এটি একটি স্পার্স ম্যাট্রিক্স।
0 0 9 5 0 8 7 0 0
অ্যালগরিদম
Begin
Declare a 2D array a[10][10] to the integer datatype.
Initialize some values of array.
Declare i, j, count to the integer datatype.
Initialize count = 0.
Declare row, col to the integer datatype.
Initialize row = 3, col = 3.
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
if (a[i][j] == 0)
count++.
Print “The matrix is:” .
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
Print the values of array.
Print “The number of zeros in the matrix are”.
if (count > ((row * col)/ 2)) then
Print "This is a sparse matrix".
else
Print "This is not a sparse matrix".
End. উদাহরণ
#include<iostream>
using namespace std;
int main () {
int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} };
int i, j, count = 0;
int row = 3, col = 3;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
if (a[i][j] == 0)
count++;
}
}
cout<<"The matrix is:"<<endl;
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j) {
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<"The number of zeros in the matrix are "<< count <<endl;
if (count > ((row * col)/ 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;
return 0;
} আউটপুট
The matrix is: 0 0 9 5 0 8 7 0 0 The number of zeros in the matrix are 5 This is a sparse matrix