# Count quadruples from four sorted arrays whose sum is equal to a given value x in C++

We are given four arrays A[], B[], C[] and D[]. The goal is to find all quadruples of elements of these arrays such that A[i]+B[j]+C[k]+D[l] =x. All four arrays have the same number of elements N.

We will do this by traversing each array once and compare if A[i]+B[j]+C[j]+D[l]==x. If true increment count.

Let’s understand with examples.

Input

A[]={ 1,2,3}; B[]={ 2,3,2}; C[]={ 4,3,1}; D[]={ 3,1,1 }; X=12

Output

Count of Quadruples: 4

Explanation

Quadruples such as ( A[i] B[j] C[k] D[l] ) are:
(2 3 4 3) , (3 2 4 3), (3 3 3 3), (3 2 4 3)
Number of quadruples : 4

Input

A[]={ 1,1,1}; B[]={ 2,2,2}; C[]={ 3,3,3}; D[]={ 4,4,4 }; X=15

Output

Count of Quadruples: 0

Explanation

No such elements could be paired.

## Approach used in the below program is as follows

• We take integer arrays A[],B[], C[] and D[] of equal length initialized with random numbers.

• Take variable N to store their length.

• Function countQuad(int a[],int b[],int c[],d[],int x, int n) takes all arrays as input with their same length n and returns count.

• Traverse using four loops for each array.

• Outermost loop 0<=i<n for a[], inner 0<=j<n for b[], other 0<=k<n for c[] and innermost 0<=l

• Compare if a[i]+b[j]+c[k]+d[l]==x. If true increment count.

• At the end of all loops count will have quadruples with sum x.

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int countQuads(int a[],int b[],int c[],int d[],int x, int n){
int count = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
for (int k = 0; k < n; k++){
for (int l = 0; l < n; l++){
int sum=a[i]+b[j]+c[k]+d[l];
if(sum==x){
count++;
cout<<endl<<a[i]<<" "<<b[j]<<" "<<c[k]<<" "<<d[l];}
}
}
}
}
return count;
}
int main(){
int A[]={ 1,1,1}; int B[]={ 2,2,2}; int C[]={ 3,3,3}; int D[]={ 4,4,4 };
int X=15;
int N=3; //length of each array
}
Number of quadruples : 0