C++ Program to print unique integer pairs

C++Server Side ProgrammingProgramming

Suppose, we are given two arrays a and b that each contain n integer numbers. From the arrays, we have to create integer pairs where one number is from array a and another one is from array b, and the addition of the numbers is always unique. We print all such integer pairs.

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.

https://www.tutorialspoint.com/data_structures_algorithms/greedy_algorithms.htm

https://www.tutorialspoint.com/data_structures_algorithms/dynamic_programming.htm

So, if the input of our problem is like n = 6, a = {7, 6, 5, 2, 1, 4}, b = {2, 4, 8, 9, 3, 6}, then the output will be

1,2
2,3
4,4
5,6
6,8
7,9

Steps

To solve this, we will follow these steps −

sort the array a
sort the array b
for initialize i := 0, when i < n, update (increase i by 1), do:
   print(a[i], b[i])

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
void solve(int n, int a[], int b[]) {
   sort(a, a + n);
   sort(b, b + n);
   for(int i = 0; i < n; i++)
      cout<< a[i] << "," << b[i] << endl;
}
int main() {
   int n = 6, a[] = {7, 6, 5, 2, 1, 4}, b[] = {2, 4, 8, 9, 3, 6};
   solve(n, a, b);
   return 0;
}

Input

6, {7, 6, 5, 2, 1, 4}, {2, 4, 8, 9, 3, 6}

Output

1,2
2,3
4,4
5,6
6,8
7,9
raja
Updated on 07-Apr-2022 08:57:46

Advertisements