เราได้รับสี่อาร์เรย์ เป้าหมายคือการหาสี่เท่าขององค์ประกอบจากสี่อาร์เรย์ที่มีผลรวมเท่ากับค่ารวมที่กำหนด องค์ประกอบที่เลือกควรเป็นแบบที่ทั้ง 4 องค์ประกอบเป็นของอาร์เรย์ที่แตกต่างกัน
เราจะทำสิ่งนี้โดยสำรวจอาร์เรย์ทั้งหมดโดยใช้ for loop และตรวจสอบว่า 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_size, second_size, third_size, four_size เพื่อจัดเก็บความยาวตามลำดับ
-
ใช้ผลรวมตัวแปรสำหรับค่าผลรวมที่กำหนด
-
ฟังก์ชัน quadruplets(int first[], int second[], int third[], int four[], int first_size, int second_size, int third_size, int Four_size, int sum) รับอาร์เรย์ทั้งหมดและความยาวด้วยผลรวมและจำนวนที่ส่งคืน สี่เท่าด้วยผลรวมที่กำหนด
-
สำรวจแต่ละอาร์เรย์โดยใช้ FOR ลูป
-
วงนอกสุด 0<=i
-
เปรียบเทียบ if first[i] + second[j] + third[k] + four[l] ==sum. ถ้านับเพิ่มจริง
-
เมื่อสิ้นสุดการวนซ้ำทั้งหมดจะมีสี่เท่าด้วยผลรวมที่กำหนด
-
ผลตอบแทนนับเป็นผลลัพธ์
ตัวอย่าง
#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