배열 중복 확인

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어를 사용하여 주어진 배열에 중복된 요소가 있는지 여부를 확인하는 방법을 배우겠습니다. 이는 배열을 정렬한 다음 인접한 요소를 비교하여 동일성을 확인하는 방식으로 수행됩니다.

라이브러리 및 메인 함수 작성

다음과 같이 라이브러리와 메인 함수를 작성합니다.

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

bool containsDuplicate(int n[], int m)
{
    // Create a flag to indicate the presence of duplicate
    int f = 0;

    // Sort the input array to check for duplicates
    sort(n, n + m);

    for (int i = 0; i < m - 1; i++)
    {
        if (n[i] == n[i + 1])
        {
            // set the flag to 1 and exit the loop if dupliate is found
            f = 1;
            break;
        }
    }

    if (f == 1) {
        // Duplicate found
        return true;
    }
    else {
        // No duplicates found
        return false;
    }
}

int main()
{
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " ===== Program to check if any duplicates are present in the input array  ===== \n\n";

    int i, n1, n2;

    int a1[] = {2, 3, 1, 4, 5, 2, 8, 9};
    int a2[] = {2, 3, 1, 4, 5, 10, 8, 9};

    bool duplicate1 = false;
    bool duplicate2 = false;

    // Get the size of the two input arrays
    n1 = sizeof(a1) / sizeof(a1[0]);
    n2 = sizeof(a2) / sizeof(a2[0]);

    // Print the first input array
    cout << "\n\nThe elements of the first input array are :\n\n";

    for (i = 0; i < n1; i++)
    {
        cout << a1[i] << "  ";
    }

    // Check if the first input array contains duplicates
    duplicate1 = containsDuplicate(a1, n1);

    if (duplicate1) {
        cout << "\n\nThe first input array contains duplicate";
    }
    else {
        cout << "\n\nThe first input array does not contain any duplicate";
    }

    // Print the second input array
    cout << "\n\n\n\nThe elements of the second input array are :\n\n";

    for (i = 0; i < n2; i++)
    {
        cout << a2[i] << "  ";
    }

    // Check if the second input array contains duplicates
    duplicate2 = containsDuplicate(a2, n2);

    if (duplicate2) {
        cout << "\n\nThe second input array contains duplicate";
    }
    else {
        cout << "\n\nThe second input array does not contain any duplicate";
    }

    cout << "\n\n\n";

    return 0;
}

코드 실행

코드를 ~/project/main.cpp 파일에 저장하고, 다음 명령을 사용하여 코드를 컴파일합니다.

g++ main.cpp -o main && ./main

코드 이해

배열에서 중복을 확인하기 위해 먼저 containsDuplicate()라는 함수를 만들었습니다. 이 함수는 두 개의 인수를 받습니다. 입력 배열 n[]과 크기 m입니다.
이 함수는 중복을 발견하면 값 1로, 그렇지 않으면 값 0으로 플래그를 설정합니다. 중복을 찾기 위해 입력 n[]은 먼저 시스템 정의 sort() 함수를 사용하여 정렬됩니다. 그런 다음, 정렬된 배열에서 인접한 요소들을 비교하고, 중복이 발견되면 플래그가 설정됩니다.
메인 함수에서는 두 개의 테스트 배열 a1a2가 생성되며, 각 배열은 잠재적인 중복을 가지고 있습니다. containsDuplicate()를 사용하여 각 배열에서 중복을 확인하고 결과를 출력합니다.

if (duplicate1) {
    cout << "\n\nThe first input array contains duplicate";
}
else {
    cout << "\n\nThe first input array does not contain any duplicate";
}

이 출력은 입력 배열에 중복이 있는지 여부를 나타냅니다.

요약

C++ 프로그래밍을 사용하여 배열 내의 중복을 쉽게 확인할 수 있습니다. 입력 배열을 정렬한 다음 인접한 요소를 비교함으로써 중복 값을 나타내는 효율적인 플래깅 시스템을 개발할 수 있습니다.