Giới thiệu
Trong bài viết này, chúng ta sẽ tìm hiểu cách xác định xem một ma trận có phải là ma trận thưa (sparse matrix) hay không. Ma trận được gọi là thưa nếu hầu hết các phần tử của nó đều là 0, nghĩa là chứa rất ít phần tử khác 0.
Minh họa
Đầu vào:
Input matrix: 4 0 6 0 0 9 6 0 0
Đầu ra mong muốn:
Yes, the matrix is a sparse matrix
Thuật toán
- Bắt đầu
- Khai báo ma trận số nguyên
input_matrix - Khởi tạo giá trị
- Duyệt từng phần tử bằng 2 vòng lặp
forlồng nhau, đếm số phần tử bằng 0 - Nếu số phần tử 0 lớn hơn nửa tổng số phần tử → ma trận thưa, ngược lại thì không
- Hiển thị kết quả
- Kết thúc
Ví dụ 1: Triển khai trong hàm 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");
}
}
Đầu ra
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix
Ví dụ 2: Tách hàm static (OOP)
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);
}
}
Đầu ra
The matrix is defined as: 4 0 6 0 0 9 6 0 0 Yes, the matrix is a sparse matrix