Menu
Coddy logo textTech

Math - Union of HashSets

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

합집합 연산은 두 집합을 결합하여 두 집합 모두의 모든 요소를 중복 없이 포함하는 새로운 집합을 생성합니다.

두 개의 HashSet을 생성하세요:

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

Union 메서드를 사용하여 집합을 결합하세요:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

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

[1, 2, 3, 4, 5]

요소 3이 결과에서 한 번만 나타나는 것을 주목하세요. HashSet은 중복을 허용하지 않기 때문입니다.

challenge icon

챌린지

쉬움

두 개의 정수 HashSet을 매개변수로 받아 두 집합의 합집합을 포함하는 새로운 HashSet을 반환하는 UnionSets라는 이름의 메서드를 생성하세요.

입력 읽기와 출력 출력은 이미 처리되어 있으니 UnionSets 메서드 본문 구현에 집중하세요.

치트 시트

Union 연산은 두 집합을 결합하여 중복 없이 두 집합의 모든 요소를 포함하는 새로운 집합을 만듭니다.

두 개의 HashSet을 생성하세요:

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

Union 메서드를 사용하여 집합을 결합하세요:

HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);

결과는 두 집합의 모든 고유 요소를 포함합니다. 중복은 자동으로 제거됩니다.

직접 해보기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    public static HashSet<int> UnionSets(HashSet<int> set1, HashSet<int> set2)
    {
        // 여기에 코드를 작성하세요
        return null;
    }
    
    static void Main(string[] args)
    {
        // 첫 번째 집합의 형식을 확인하기 위해 첫 번째 줄을 읽습니다
        string line1 = Console.ReadLine();
        HashSet<int> set1 = new HashSet<int>();
        
        // 첫 번째 집합이 JSON 배열 형식인지 확인합니다
        if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]"))
        {
            try
            {
                // 대괄호 사이의 내용을 추출합니다
                string arrayContent = line1.Substring(1, line1.Length - 2);
                
                // JSON 배열 내용을 파싱해 봅니다
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // 따옴표가 있으면 제거합니다
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // 정수로 파싱하여 집합에 추가합니다
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set1.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing first set: {ex.Message}");
                return;
            }
        }
        else
        {
            // 첫 번째 집합에 대해 전통적인 공백으로 구분된 입력을 처리합니다
            string[] input1 = line1.Split(' ');
            foreach (string num in input1)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set1.Add(parsedNum);
                }
            }
        }
        
        // 두 번째 집합의 형식을 확인하기 위해 두 번째 줄을 읽습니다
        string line2 = Console.ReadLine();
        HashSet<int> set2 = new HashSet<int>();
        
        // 두 번째 집합이 JSON 배열 형식인지 확인합니다
        if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]"))
        {
            try
            {
                // 대괄호 사이의 내용을 추출합니다
                string arrayContent = line2.Substring(1, line2.Length - 2);
                
                // JSON 배열 내용을 파싱해 봅니다
                string[] values = Regex.Split(arrayContent, @",\s*");
                foreach (string value in values)
                {
                    // 따옴표가 있으면 제거합니다
                    string cleanValue = value.Trim();
                    if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
                    {
                        cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
                    }
                    
                    // 정수로 파싱하여 집합에 추가합니다
                    if (int.TryParse(cleanValue, out int num))
                    {
                        set2.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing second set: {ex.Message}");
                return;
            }
        }
        else
        {
            // 두 번째 집합에 대해 전통적인 공백으로 구분된 입력을 처리합니다
            string[] input2 = line2.Split(' ');
            foreach (string num in input2)
            {
                if (int.TryParse(num, out int parsedNum))
                {
                    set2.Add(parsedNum);
                }
            }
        }
        
        // 합집합을 구하고 결과를 출력합니다
        HashSet<int> unionSet = UnionSets(set1, set2);
        Console.WriteLine(string.Join(" ", unionSet.OrderBy(x => x)));
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨