เมทริกซ์กระจัดกระจายเป็นเมทริกซ์ที่องค์ประกอบส่วนใหญ่เป็น 0 ตัวอย่างสำหรับสิ่งนี้มีดังต่อไปนี้
เมทริกซ์ที่ระบุด้านล่างมีศูนย์ 5 ตัว เนื่องจากจำนวนศูนย์มีมากกว่าครึ่งหนึ่งขององค์ประกอบของเมทริกซ์ จึงเป็นเมทริกซ์แบบกระจาย
5 0 0 3 0 1 0 0 9
โปรแกรมที่จะใช้เมทริกซ์กระจัดกระจายมีดังนี้
ตัวอย่าง
#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
ในโปรแกรมข้างต้น nested for loop ใช้เพื่อนับจำนวนศูนย์ในเมทริกซ์ ซึ่งแสดงให้เห็นโดยใช้ข้อมูลโค้ดต่อไปนี้
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;