在C ++中具有给定总和的四元组计数
我们有四个数组。目标是从四个数组中找到总和等于给定Sum值的元素四元组。选择的元素应确保所有4个元素属于不同的数组。
我们将使用for循环遍历所有数组并检查A[i]+B[j]+C[k]+D[l]==sum。如果是,则增加计数。
让我们通过示例来理解-
输入-
A[]={ 1,3,1}, B[]={ 2,4,5 } , C[]={ 1,1,2 } , D[]= { 4,4,0} Sum=5输出-给定总和的四元组计数为-2
说明-
2 quadrutplets are: (A[0],B[0],C[2],D[2]) → (1,2,2,0), sum=5 (A[2],B[0],C[2],D[2]) → (1,2,2,0), sum=5
输入-
A[]={ 1,1,1}, B[]={ 1,1,1 } , C[]={ 1,1,1 } , D[]= {1,1,1} Sum=3输出-给定总和的四元组计数为-0
说明-所有四倍数的总和将是4,即>3。
以下程序中使用的方法如下
我们采用相等长度的整数数组first[],second[],third[]和fourth[],并用随机数初始化。
取变量first_size,second_size,third_size,fourth_size来存储它们各自的长度。
给定总和值取可变总和。
函数quadruplets(intfirst[],intsecond[],intthird[],intfour[],intfirst_size,intsecond_size,intthird_size,intfour_size,intsum)接受所有数组及其长度与sum并返回计数给定总和的四元组。
使用FOR循环遍历每个数组
最外层的循环对于first[]为0<=i<first_size,然后对于second[]为0<=j<second_size,对于Third[]为0<=k<third_size,对于first[]为0<=l<fourth_size。
比较first[i]+second[j]+Third[k]+Fourth[l]==和。如果为真,则递增计数。
在所有循环结束时,计数将具有具有给定总和的四元组。
返回计数作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int quadruplets(int first[], int second[], int third[], int fourth[], int first_size, int second_size, int
third_size, int fourth_size, int sum){
int count = 0;
for (int i = 0; i < first_size; i++){
for (int j = 0; j < second_size; j++){
for (int k = 0; k < third_size; k++){
for (int l = 0; l < fourth_size; l++){
if (first[i] + second[j] + third[k] + fourth[l] == sum){
count++;
}
}
}
}
}
return count;
}
int main(){
int first[] = { 7, -8 };
int second[] = { 7, -2 };
int third[] = { 4, -2 };
int fourth[] = { 3, -4 };
int first_size = sizeof(first) / sizeof(first[0]);
int second_size = sizeof(second) / sizeof(second[0]);
int third_size = sizeof(third) / sizeof(third[0]);
int fourth_size = sizeof(fourth) / sizeof(fourth[0]);
int sum= 0;
cout<<"Count of quadruplets with given sum are: "<<quadruplets(first, second, third, fourth, first_size, second_size, third_size, fourth_size, sum);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of quadruplets with given sum are: 1