Sparse matrix คือเมทริกซ์ที่ส่วนใหญ่ของสมาชิกเป็น 0 ตัวอย่างเมทริกซ์ด้านล่างมี 0 ทั้งหมด 5 ตัว เนื่องจากจำนวน 0 มากกว่าครึ่งหนึ่งของสมาชิกทั้งหมด จึงเป็น sparse matrix
0 0 9 5 0 8 7 0 0
อัลกอริทึม
เริ่มต้น
ประกาศอาร์เรย์ 2D a[10][10] ชนิด integer
กำหนดค่าเริ่มต้นบางส่วน
ประกาศ i, j, count ชนิด integer
กำหนด count = 0
ประกาศ row, col ชนิด integer
กำหนด row = 3, col = 3
สำหรับ (i = 0; i < row; ++i)
สำหรับ (j = 0; j < col; ++j)
ถ้า (a[i][j] == 0) แล้ว
count++
จบถ้า
จบลูป
จบลูป
พิมพ์ "The matrix is: "
สำหรับ (i = 0; i < row; ++i)
สำหรับ (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