ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีเขียนโปรแกรมสำหรับยูเนี่ยนและจุดตัดของอาร์เรย์ที่ไม่เรียงลำดับสองตัว มาดูตัวอย่างกัน
ป้อนข้อมูล
arr_one = [1, 2, 3, 4, 5] arr_two = [3, 4, 5, 6, 7]
ผลผลิต
union: 1 2 3 4 5 6 7 intersection: 3 4 5
มาดูขั้นตอนการแก้ปัญหากัน
ยูเนี่ยน
-
เริ่มต้นสองอาร์เรย์ด้วยค่าสุ่ม
-
สร้างอาร์เรย์ว่างที่เรียกว่า union_result
-
วนซ้ำในอาร์เรย์แรกและเพิ่มทุกองค์ประกอบเข้าไป
-
วนซ้ำในอาร์เรย์ของส่วนและเพิ่มองค์ประกอบหากไม่มีอยู่ในอาร์เรย์ union_result
-
พิมพ์อาร์เรย์ union_result
สี่แยก
-
เริ่มต้นสองอาร์เรย์ด้วยค่าสุ่ม
-
สร้างอาร์เรย์ว่างที่เรียกว่า intersection_result
-
วนซ้ำในอาร์เรย์แรกและเพิ่มองค์ประกอบหากมีอยู่ในอาร์เรย์ที่สอง
-
พิมพ์อาร์เรย์ intersection_result
ตัวอย่าง
ดูโค้ดด้านล่าง
#include <bits/stdc++.h>
using namespace std;
int isElementPresentInArray(int arr[], int arr_length, int element) {
for (int i = 0; i < arr_length; ++i) {
if (arr[i] == element) {
return true;
}
}
return false;
}
void findUnionAndIntersection(int arr_one[], int arr_one_length, int arr_two[], int arr_two_length) {
// union
int union_result[arr_one_length + arr_two_length] = {};
for (int i = 0; i < arr_one_length; ++i) {
union_result[i] = arr_one[i];
}
int union_index = arr_one_length;
for (int i = 0; i < arr_two_length; ++i) {
if (!isElementPresentInArray(arr_one, arr_one_length, arr_two[i])) {
union_result[union_index++] = arr_two[i];
}
}
cout << "Union: ";
for (int i = 0; i < union_index; ++i) {
cout << union_result[i] << " ";
}
cout << endl;
// intersection
int intersection_result[arr_one_length + arr_two_length] = {};
int intersection_index = 0;
for (int i = 0; i < arr_one_length; ++i) {
if (isElementPresentInArray(arr_two, arr_two_length, arr_two[i])) {
intersection_result[intersection_index++] = arr_one[i];
}
}
cout << "Intersection: ";
for (int i = 0; i < intersection_index; ++i) {
cout << intersection_result[i] << " ";
}
cout << endl;
}
int main() {
int arr_one[] = {1, 2, 3, 4, 5};
int arr_two[] = {3, 4, 5, 6, 7};
findUnionAndIntersection(arr_one, 5, arr_two, 5);
return 0;
} ผลลัพธ์
หากคุณรันโปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังต่อไปนี้
Union: 1 2 3 4 5 6 7 Intersection: 1 2 3 4 5
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น