Trong hướng dẫn này, ta sẽ học cách viết chương trình tìm hợp và giao của hai mảng chưa sắp xếp. Hãy xem ví dụ.
Đầu vào
arr_one = [1, 2, 3, 4, 5] arr_two = [3, 4, 5, 6, 7]
Đầu ra
union: 1 2 3 4 5 6 7 intersection: 3 4 5
Hãy xem các bước giải quyết.
Hợp (Union)
- Khởi tạo hai mảng với giá trị ngẫu nhiên.
- Tạo mảng rỗng union_result.
- Duyệt mảng thứ nhất, thêm mọi phần tử vào union_result.
- Duyệt mảng thứ hai, thêm phần tử nếu chưa có trong union_result.
- In union_result.
Giao (Intersection)
- Khởi tạo hai mảng với giá trị ngẫu nhiên.
- Tạo mảng rỗng intersection_result.
- Duyệt mảng thứ nhất, thêm phần tử nếu nó có trong mảng thứ hai.
- In intersection_result.
Ví dụ
Xem mã dưới đây:
#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; }
Đầu ra
Nếu thực thi chương trình trên, bạn sẽ nhận được kết quả sau:
Union: 1 2 3 4 5 6 7 Intersection: 1 2 3 4 5
Kết luận
Nếu bạn có thắc mắc, hãy đề cập trong phần bình luận.