Sparse Matrix คือเมทริกซ์ที่ส่วนใหญ่ขององค์ประกอบเป็น 0 กล่าวคือ หากจำนวนศูนย์มากกว่าครึ่งหนึ่งขององค์ประกอบทั้งหมด จะเรียกว่า Sparse Matrix
ตัวอย่าง เมทริกซ์ 3×3 มี 5 ศูนย์ (มากกว่า 9/2 = 4.5) → Sparse Matrix:
1 0 2 5 0 0 0 0 9
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int a[10][10] = { {2, 0, 0}, {0, 3, 8}, {0, 9, 0} };
int i, j, count = 0;
int r = 3, c = 3;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
if (a[i][j] == 0)
count++;
}
}
cout << "The matrix is:" << endl;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
cout << a[i][j] << " ";
}
cout << endl;
}
cout << "There are " << count << " zeros in the matrix" << endl;
if (count > ((r * c) / 2))
cout << "This is a sparse matrix" << endl;
else
cout << "This is not a sparse matrix" << endl;
return 0;
}
ผลลัพธ์
The matrix is: 2 0 0 0 3 8 0 9 0 There are 5 zeros in the matrix This is a sparse matrix
อธิบายโค้ด
นับจำนวนศูนย์ด้วย nested loop:
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
if (a[i][j] == 0)
count++;
}
}
แสดงเมทริกซ์:
cout<<"The matrix is:"<<endl;
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
ตัดสินว่า Sparse Matrix หรือไม่:
cout<<"There are "<<count<<" zeros in the matrix"<<endl;
if (count > ((r * c) / 2))
cout<<"This is a sparse matrix"<<endl;
else
cout<<"This is not a sparse matrix"<<endl;