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 分別儲存它們的長度。

  • 獲取變數 sum 用於儲存給定的和值。

  • 函式 quadruplets(int first[], int second[], int third[], int fourth[], int first_size, int second_size, int third_size, int fourth_size, int sum) 獲取所有陣列及其長度以及和,並返回給定和的四元組計數。

  • 使用 FOR 迴圈遍歷每個陣列

  • 最外層迴圈 0<=i<first_size 用於 first[],然後 0<=j<second_size 用於 second[],0<=k<third_size 用於 third[],以及 0<=l<fourth_size 用於 fourth[]。

  • 比較 first[i] + second[j] + third[k] + fourth[l] == sum。如果為真,則遞增計數。

  • 在所有迴圈結束時,count 將包含給定和的四元組。

  • 返回 count 作為結果。

示例

 現場演示

#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

更新於: 2020-08-31

149 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.