Wednesday, 18 October 2017

Find All Pair with given sum in the array And Store it For later Use Problem Solution Using C++

Input: 
           range = 6
           sum = 10
          ar = [7,6,8,3,2,4]
Output:
          Pair Found At Index 0 And 3
          Pair Found At Index 1 And 5
          Pair Found At Index 2 And 4

Solution: 

#include<bits/stdc++.h>
using namespace std;
/*
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){
    int n,sum,indx = 0;
    bool flag = true;
    vector<int>ar;
    map<int,map<int,int> >m;
    cin >> n >> sum;

    for(int a, i = 0; i < n; i++){
        cin >> a;
        ar.push_back(a);
    }
    for(int i = 0; i < n; i++){
        for(int j = i+1; j < n; j++){
            if(ar[i] + ar[j] == sum){
                flag = false;
                m[indx++][i] =j;
            }
        }
    }
    if(flag)cout << "Pair Not Found." << endl;
    else {
        for(map<int,map<int,int> >::iterator i = m.begin(); i != m.end(); ++i){
            for(map<int,int>::iterator j = i->second.begin(); j != i->second.end(); j++){
                cout << "Pair Found At Index " << j->first << " And " << j->second << endl;
            }
        }
    }
    return 0;
}

Find All Pair with given sum in the array Problem Solution Using C++.

Input: 
           range = 6
           sum = 10
          ar = [3,5,4,8,2,3]
Output:
          Pair Found At Index 3 And 4

OR
Input: 
        range = 6
        sum = 10
        ar = [3,7,5,5,2,8]
Output:
        Pair Found At Index 0 And 1
        Pair Found At Index 2 And 3

        Pair Found At Index 4 And 5

Solution:

#include<bits/stdc++.h>
using namespace std;
/*
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){
    int n,sum;
    bool flag = true;
    vector<int>ar;
    cin >> n >> sum;

    for(int a, i = 0; i < n; i++){
        cin >> a;
        ar.push_back(a);
    }
    for(int i = 0; i < n; i++){
        for(int j = i+1; j < n; j++){
            if(ar[i] + ar[j] == sum){
                flag = false;
                cout << "Pair Found At Index " << i << " And " << j << endl;
            }
        }
    }
    if(flag)cout << "Pair Not Found." << endl;
    return 0;
}

Find First Pair with given sum in the array Problem Solution Using C++

Input: 
           range = 6
           sum = 10
          ar = [3,6,8,5,4,2]
Output:
          Pair Found At Index 1 And 4

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main() {
 int n, ar[10000],sum;
 cin >> n >> sum;

 for(int i = 0; i < n; i++){
  cin >> ar[i];
 }
 for(int i = 0; i < n; i++){
  for(int j = i+1; j < n; j++){
   if(ar[i] + ar[j] == sum){
    cout << "Pair Found At Index " << i << " And " << j << endl;
    return 0;
   }
  }
 }
 cout << "Pair Not Found." << endl;
 return 0;
}