একটি স্পার্স ম্যাট্রিক্স (sparse matrix) হলো এমন একটি ম্যাট্রিক্স যেটির অধিকাংশ উপাদান ০। নিচে একটি উদাহরণ দেওয়া হলো।
নিচের ম্যাট্রিক্সে ৫টি ০ রয়েছে। যেহেতু ০-এর সংখ্যা ম্যাট্রিক্সের মোট উপাদানের অর্ধেকের চেয়ে বেশি, তাই এটি একটি স্পার্স ম্যাট্রিক্স।
0 0 9 5 0 8 7 0 0
অ্যালগরিদম
শুরু
a[10][10] 2D অ্যারে ইন্টিজার টাইপে ডিক্লেয়ার করুন
অ্যারের কিছু মান ইনিশিয়ালাইজ করুন
i, j, count ইন্টিজার টাইপে ডিক্লেয়ার করুন
count = 0 ইনিশিয়ালাইজ করুন
row, col ইন্টিজার টাইপে ডিক্লেয়ার করুন
row = 3, col = 3 ইনিশিয়ালাইজ করুন
for (i = 0; i < row; ++i) {
for (j = 0; j < col; ++j)
if (a[i][j] == 0)
count++
"The matrix is:" প্রিন্ট করুন
for (i = 0; i < row; ++i)
for (j = 0; j < col; ++j)
অ্যারের মান প্রিন্ট করুন
"The number of zeros in the matrix are" প্রিন্ট করুন
যদি (count > ((row * col) / 2)) হয়, তবে
"This is a sparse matrix" প্রিন্ট করুন
অন্যথায়
"This is not a sparse matrix" প্রিন্ট করুন
শেষ
উদাহরণ কোড
#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