Sunday, 9 November 2014

Sum of 4 number in a Array equal to a given number

Print combination of 4 numbers which is equal to a given number (say total).

Algorithm:
  • Sort the array
  • Loop in array assuming first 2 elements(index i,k) are part of valid combination and than finding other 2 elements(index l,r) in array ,a whose sum is equal to total- a[i]-a[k].
  • Loop while l < r.
           (a) If (A[l] + A[r] == remaning sum)  then print & l++,r--                                        (b) Else if( A[l] + A[r] <  remaining sum )  then l++
           (c) Else r--
  • Do Step 2 and 3 taking other combinations of 2 elements
Implementation
 #include<stdio.h>  
 #include<string.h>  
 #include<iostream>  
 #include<algorithm>  
 using namespace std;  
 void ValidCombo(int n,int a[],int sum)  
 {  
   int temp,flag=0;  
   string str;  
   sort(a,a+n);  
   for(int i=0;i<n;i++)  
   {  
     for(int k=i+1;k<n;k++)  
     {  
       temp= a[i]+a[k];  
       int l, r,count=0;  
       l = k+1;  
       r = n-1;  
       while(l < r)  
       {  
         if(a[l] + a[r] == sum-temp)  
         {  
           cout<<a[i]<<" "<<a[k]<<" "<<a[l]<<" "<<a[r]<<"\n";  
           flag=1;  
           l++;  
           r--;  
         }  
         else if(a[l] + a[r] < sum-temp)  
           l++;  
         else  
           r--;  
       }   
     }  
   }  
   if(flag==0)  
     cout<<"Valid Combination not Possible";  
 }  
 int main()  
 {  
   int n,total;  
   cin>>n;  
   int *a=new int[n];  
   for(int i=0;i<n;i++)  
     cin>>a[i];  
   cin>>total;  
   ValidCombo(n,a,total);  
   delete a;  
   return 0;  
 }  
Please comment if you find anything incorrect.

No comments:

Post a Comment