이 튜토리얼에서는 정렬되지 않은 두 배열의 합집합과 교집합을 위한 프로그램을 작성하는 방법을 배울 것입니다. 예를 들어 보겠습니다.
입력
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
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.