与えられた行列がスパース行列であるかどうかを判断するJavaプログラム
この記事では、特定の行列がスパース行列であるかどうかを判断する方法を理解します。行列のほとんどの要素が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
-
範囲が指定されている場合に文字列を展開するJavaプログラム?
範囲が指定されている場合に文字列を展開するには、Javaコードは次のとおりです- 例 public class Demo { public static void expand_range(String word) { StringBuilder my_sb = new StringBuilder(); String[] str_arr = word.split(", "); for (int i = 0; i < s
-
与えられた数がフィボナッチ数であるかどうかをチェックするためのJavaプログラム?
以下は、指定された番号がフィボナッチであるかどうかを確認するJavaプログラムです- 例 public class Demo{ static boolean perfect_square_check(int val){ int s = (int) Math.sqrt(val); return (s*s == val); } static boolean fibonacci_num_check(int n){