একটি ম্যাট্রিক্স row x col দেওয়া আছে। লক্ষ্য হল ম্যাট্রিক্সের যেসব সেল নিচের শর্ত পূরণ করে, তাদের সংখ্যা বের করা:
সেলের মান + সংলগ্ন সেলের সংখ্যা = একটি ফিবোনাচ্চি সংখ্যা
ফিবোনাচ্চি সিরিজ: ০, ১, ১, ২, ৩, ৫, ৮, ১৩, ২১, ৩৪ ...
উদাহরণ দিয়ে বোঝা যাক
ইনপুট - matrix[3][3] = {{1,4,1}, {2,0,1}, {5,1,1}}
আউটপুট - শর্ত পূরণকারী সেলের সংখ্যা: ৪
ব্যাখ্যা
| 0 | 1 | 2 | |
|---|---|---|---|
| 0 | 1 | 4 | 1 |
| 1 | 2 | 0 | 1 |
| 2 | 5 | 1 | 1 |
- Cell(0,0) → 1+2=3 (২টি সংলগ্ন সেল: (1,0) এবং (0,1))
- Cell(0,2) → 1+2=3
- Cell(1,0) → 2+3=5
- Cell(2,2) → 1+2=3
ইনপুট - matrix[3][3] = {{0,0,0}, {0,1,0}, {0,0,0}}
আউটপুট - শর্ত পূরণকারী সেলের সংখ্যা: ৯
ব্যাখ্যা - সব ৯টি সেল শর্ত পূরণ করে।
প্রোগ্রামে ব্যবহৃত পদ্ধতি
কোনো ম্যাট্রিক্সে তিন ধরনের সেল থাকে: কনারের সেল (২টি সংলগ্ন), এজের সেল (৩টি সংলগ্ন), এবং ইন্টারন্যাল সেল (৪টি সংলগ্ন)। এই সেলগুলোর মান সাথে ২, ৩ বা ৪ যোগ করে চেক করা হয় যে যোগফল ফিবোনাচ্চি সংখ্যা কিনা check_fibonacci(int num) ফাংশন দিয়ে।
- ম্যাট্রিক্স ইনিশিয়ালাইজ করুন।
- ফাংশন
check_square(long double num)নম্বরটি পারফেক্ট স্কয়ার কিনা চেক করে। - ফাংশন
check_fibonacci(int num)নম্বরটি ফিবোনাচ্চি কিনা চেক করে।5*num*num+4বা5*num*num-4পারফেক্ট স্কয়ার হলে ফিবোনাচ্চি। - ফাংশন
Fibonacci_cells(int matrix[row][col])শর্ত পূরণকারী সেল কাউন্ট রিটার্ন করে। - প্রাথমিক কাউন্ট ০।
- i=0 থেকে row-১, j=0 থেকে col-১ পর্যন্ত ডাবল FOR লুপ।
total = matrix[i][j]। সেলের টাইপ অনুযায়ী ২, ৩ বা ৪ যোগ করুন।- যদি
check_fibonacci(total)true হয় তবে কাউন্ট বাড়ান। - সব লুপ শেষে কাউন্ট রিটার্ন করুন।
উদাহরণ কোড
#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 3
bool check_square(long double num) {
long double val = sqrt(num);
return ((val - floor(val)) == 0);
}
bool check_fibonacci(int num) {
return check_square(5 * num * num + 4) || check_square(5 * num * num - 4);
}
int Fibonacci_cells(int matrix[row][col]) {
int count = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int total = matrix[i][j];
if ((i == 0 && j == 0) || (i == row-1 && j == 0) || (i == 0 && j == col-1) || (i == row-1 && j == col-1)) {
total = total + 2;
} else if (i == 0 || j == 0 || i == row-1 || j == col-1) {
total = total + 3;
} else {
total = total + 4;
}
if (check_fibonacci(total)) count++;
}
}
return count;
}
int main() {
int matrix[row][col] = {{1,4,1},{2,0,1},{5,1,1}};
cout << "Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added are: " << Fibonacci_cells(matrix);
return 0;
}
উপরের কোড রান করলে নিচের আউটপুটটি পাওয়া যাবে:
আউটপুট
Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added are: 4