ในบทความนี้ เราจะเรียนรู้วิธีการตรวจสอบว่าเมทริกซ์ (Matrix) ที่กำหนดเป็น Sparse Matrix หรือไม่ เมทริกซ์จะถูกเรียกว่า Sparse Matrix หากส่วนใหญ่ขององค์ประกอบในเมทริกซ์เป็นค่า 0 กล่าวคือ มีองค์ประกอบที่ไม่ใช่ศูนย์น้อยมาก
ตัวอย่างการทำงาน
สมมติข้อมูลนำเข้า (Input) คือ:
Input matrix: 4 0 6 0 0 9 6 0 0
ผลลัพธ์ที่ต้องการ (Output) คือ:
Yes, the matrix is a sparse matrix
อัลกอริทึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศเมทริกซ์จำนวนเต็ม input_matrix ขั้นตอนที่ 3 - กำหนดค่าให้กับเมทริกซ์ ขั้นตอนที่ 4 - วนลูปผ่านแต่ละองค์ประกอบของเมทริกซ์ด้วย for-loop 2 ชั้น นับจำนวนองค์ประกอบที่มีค่า 0 ขั้นตอนที่ 5 - ถ้าจำนวนองค์ประกอบที่เป็น 0 มากกว่าครึ่งหนึ่งขององค์ประกอบทั้งหมด ถือว่าเป็น Sparse Matrix มิฉะนั้นไม่ใช่ ขั้นตอนที่ 6 - แสดงผลลัพธ์ ขั้นตอนที่ 7 - จบการทำงาน
ตัวอย่างที่ 1: เขียนโค้ดทั้งหมดในฟังก์ชัน main
public class Sparse {
public static void main(String args[]) {
int input_matrix[][] = {
{ 4, 0, 6 },
{ 0, 0, 9 },
{ 6, 0, 0 }
};
System.out.println("The matrix is defined as: ");
int rows = 3;
int column = 3;
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < rows; ++i)
for (int j = 0; j < column; ++j)
if (input_matrix[i][j] == 0)
++counter;
if (counter > ((rows * column) / 2))
System.out.println("\nYes, the matrix is a sparse matrix");
else
System.out.println("\nNo, the matrix is not a sparse matrix");
}
}
ผลลัพธ์
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix
ตัวอย่างที่ 2: ใช้ฟังก์ชันแยก (Object-Oriented Style)
public class Sparse {
static int rows = 3;
static int column = 3;
static void is_sparse(int input_matrix[][]){
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < column; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < rows; ++i)
for (int j = 0; j < column; ++j)
if (input_matrix[i][j] == 0)
++counter;
if (counter > ((rows * column) / 2))
System.out.println("\nYes, the matrix is a sparse matrix");
else
System.out.println("\nNo, the matrix is not a sparse matrix");
}
public static void main(String args[]) {
int input_matrix[][] = { { 4, 0, 6 },
{ 0, 0, 9 },
{ 6, 0, 0 }
};
System.out.println("The matrix is defined as: ");
is_sparse(input_matrix);
}
}
ผลลัพธ์
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix