এই নিবন্ধে আমরা বুঝব কিভাবে একটি ম্যাট্রিক্স স্পার্স ম্যাট্রিক্স কিনা তা নির্ধারণ করা যায়। একটি ম্যাট্রিক্সকে স্পার্স ম্যাট্রিক্স বলা হয় যদি এর অধিকাংশ এলিমেন্ট ০ হয়। এর মানে হলো এতে খুব কম নন-জিরো এলিমেন্ট থাকে।
ডেমো
ইনপুট:
Input matrix: 4 0 6 0 0 9 6 0 0
আউটপুট:Yes, the matrix is a sparse matrix
এলগরিদম
ধাপ ১ - শুরু ধাপ ২ - একটি ইন্টিজার ম্যাট্রিক্স (input_matrix) ডিক্লেয়ার করুন ধাপ ৩ - মানগুলো সংজ্ঞায়িত করুন ধাপ ৪ - দুটি ফর-লুপ ব্যবহার করে ম্যাট্রিক্সের প্রতিটি এলিমেন্ট পরিদর্শন করুন, ০ মান যেসব এলিমেন্টের আছে তাদের সংখ্যা গণনা করুন ধাপ ৫ - যদি শূন্য এলিমেন্টের সংখ্যা মোট এলিমেন্টের অর্ধেকের চেয়ে বেশি হয়, তবে এটি একটি স্পার্স ম্যাট্রিক্স, অন্যথায় নয় ধাপ ৬ - ফলাফল প্রদর্শন করুন ধাপ ৭ - থামুন
উদাহরণ ১: মেইন ফাংশনে সব অপারেশন
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
উদাহরণ ২: অবজেক্ট-ওরিয়েন্টেড পদ্ধতিতে ফাংশন ব্যবহার
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