Menu
Coddy logo textTech

Math - Symmetric Difference

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 65번째.

두 집합의 대칭 차집합은 두 집합 중 하나에 속하지만 그들의 교집합에는 속하지 않는 요소들을 포함합니다(정확히 한 집합에만 나타나는 요소들).

두 개의 HashSet 객체를 생성하세요:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6 };

결과를 위한 새로운 HashSet을 생성하세요:

HashSet<int> symmetricDifference = new HashSet<int>(set1);

SymmetricExceptWith 메서드를 사용하여 대칭 차집합을 계산하세요:

symmetricDifference.SymmetricExceptWith(set2);

위 코드를 실행한 후, symmetricDifference 집합에는 다음이 포함됩니다:

{ 1, 2, 5, 6 }

요소 3과 4는 두 집합 모두에 있으므로 대칭 차집합에는 나타나지 않습니다.

challenge icon

챌린지

쉬움

이름이 FindSymmetricDifference인 메서드를 생성하세요. 이 메서드는 두 개의 인수를 받습니다:

  • 정수 HashSet (set1)
  • 정수 HashSet (set2)

이 메서드는 두 집합의 대칭 차집합을 포함하는 새로운 HashSet<int>을 반환해야 합니다. 프로그램의 나머지 부분(입력 읽기, 정렬, 결과 출력)은 이미 제공되어 있습니다.

치트 시트

두 집합의 대칭 차집합은 어느 한 집합에 속하지만 둘 다에는 속하지 않는 요소들을 포함합니다 (두 집합 중 정확히 하나에 나타나는 요소들).

대칭 차집합을 찾기 위해, 한 집합으로부터 새로운 HashSet을 생성하고 SymmetricExceptWith()를 사용합니다:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6 };

HashSet<int> symmetricDifference = new HashSet<int>(set1);
symmetricDifference.SymmetricExceptWith(set2);

결과: { 1, 2, 5, 6 } (요소 3과 4는 두 집합 모두에 나타나기 때문에 제외됩니다)

직접 해보기

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    public static HashSet<int> FindSymmetricDifference(HashSet<int> set1, HashSet<int> set2)
    {
        // 여기에 코드를 작성하세요
    }
    
    static void Main(string[] args)
    {
        string[] input1 = Console.ReadLine().Split(',');
        string[] input2 = Console.ReadLine().Split(',');
        
        HashSet<int> set1 = new HashSet<int>();
        HashSet<int> set2 = new HashSet<int>();
        
        foreach (string s in input1)
        {
            if (int.TryParse(s.Trim(), out int num))
            {
                set1.Add(num);
            }
        }
        
        foreach (string s in input2)
        {
            if (int.TryParse(s.Trim(), out int num))
            {
                set2.Add(num);
            }
        }
        
        HashSet<int> result = FindSymmetricDifference(set1, set2);
        
        // 결과를 오름차순으로 출력하세요
        int[] orderedResult = result.OrderBy(x => x).ToArray();
        foreach (int num in orderedResult)
        {
            Console.WriteLine(num);
        }
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 및 흐름의 모든 레슨