- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find all pairs (a,b) and (c,d) in array which satisfy ab = cd in C++
Suppose we have an array A, from that array, we have to choose two pairs (a, b) and (c, d), such that ab = cd. Let the array A = [3, 4, 7, 1, 2, 9, 8]. The output pairs are (4, 2) and (1, 8). To solve this, we will follow these steps −
- For i := 0 to n-1, do
- for j := i + 1 to n-1, do
- get product = arr[i] * arr[j]
- if product is not present in the hash table, then Hash[product] := (i, j)
- if product is present in the hash table, then print previous and current elements.
- for j := i + 1 to n-1, do
Example
#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); }
Output
(1, 6) and (2, 3) (1, 8) and (2, 4) (2, 6) and (3, 4) (3, 8) and (4, 6)
Advertisements