সমস্যা বিবরণ
একটি অ্যারে A দেওয়া আছে। সেখান থেকে দুটি জোড়া (a, b) এবং (c, d) বেছে নিতে হবে যাতে a×b = c×d হয়। ধরি অ্যারে A = [3, 4, 7, 1, 2, 9, 8]। আউটপুট জোড়াগুলো হবে (4, 2) এবং (1, 8)। এটি সমাধান করতে নিচের ধাপগুলো ফলো করতে হবে:
- i := 0 থেকে n-1 পর্যন্ত, করুন
- j := i + 1 থেকে n-1 পর্যন্ত, করুন
- product = arr[i] * arr[j] বের করুন
- যদি product হ্যাশ টেবিলে না থাকে, তবে Hash[product] := (i, j)
- যদি product হ্যাশ টেবিলে থাকে, তবে পূর্বের এবং বর্তমান এলিমেন্ট প্রিন্ট করুন।
- j := i + 1 থেকে n-1 পর্যন্ত, করুন
উদাহরণ কোড
#include <iostream>
#include <unordered_map>
using namespace std;
void displayPairs(int arr[], int n) {
bool found = false;
unordered_map<int, pair<int, int>> Hash;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int prod = arr[i] * arr[j];
if (Hash.find(prod) == Hash.end())
Hash[prod] = make_pair(i, j);
else {
pair<int, int> pp = Hash[prod];
cout << "(" << arr[pp.first] << ", " << arr[pp.second] << ") and (" << arr[i] << ", " << arr[j] << ")" << endl;
found = true;
}
}
}
if (found == false)
cout << "No pairs have Found" << endl;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = sizeof(arr) / sizeof(int);
displayPairs(arr, n);
}
আউটপুট
(1, 6) and (2, 3) (1, 8) and (2, 4) (2, 6) and (3, 4) (3, 8) and (4, 6)