이 기사에서는 주어진 행렬이 희소 행렬인지 확인하는 방법을 이해할 것입니다. 행렬의 대부분의 요소가 0인 경우 행렬을 희소 행렬이라고 합니다. 이는 0이 아닌 요소가 매우 적게 포함되어 있음을 의미합니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
Input matrix: 4 0 6 0 0 9 6 0 0
원하는 출력은 -
Yes, the matrix is a sparse matrix
알고리즘
Step 1 - START Step 2 - Declare an integer matrix namely input_matrix Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using two for-loops, count the number of elements that have the value 0. Step 5 - If the zero elements is greater than half the total elements, It’s a sparse matrix, else its not. Step 6 - Display the result. Step 7 - Stop
예시 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
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
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