এই প্রবন্ধে, আমরা বুঝতে পারব কিভাবে একটি প্রদত্ত ম্যাট্রিক্স একটি স্পার্স ম্যাট্রিক্স কিনা তা নির্ধারণ করতে হবে। একটি ম্যাট্রিক্সকে স্পার্স ম্যাট্রিক্স বলা হয় যদি সেই ম্যাট্রিক্সের বেশিরভাগ উপাদান 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
এখানে, আমরা 'প্রধান' ফাংশনের অধীনে সমস্ত ক্রিয়াকলাপ একসাথে আবদ্ধ করি।
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