Menu
Coddy logo textTech

Math - Intersection of HashSet

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

두 집합의 교집합은 두 집합에 모두 나타나는 요소만 포함합니다.

두 개의 HashSet을 생성하세요:

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

교집합을 찾기 위해 IntersectWith 메서드를 사용하세요:

set1.IntersectWith(set2);

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

{ 3, 4, 5 }

IntersectWith 메서드는 호출된 집합을 수정하여 두 집합에 모두 존재하는 요소만 유지합니다.

원본 세트를 수정하지 않고 교집합으로 새로운 세트를 생성하려면 다음을 사용할 수 있습니다:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);
challenge icon

챌린지

중급

FindCommonElements라는 이름의 메서드를 생성하여 두 개의 인수를 받도록 하세요:

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

이 메서드는 두 집합에 모두 나타나는 요소들만 포함하는 새로운 HashSet을 반환해야 합니다 (교집합).

치트 시트

두 집합의 교집합은 두 집합 모두에 나타나는 요소만 포함합니다.

교집합을 찾기 위해 IntersectWith 메서드를 사용하세요:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };
set1.IntersectWith(set2); // set1 now contains { 3, 4, 5 }

IntersectWith 메서드는 원본 집합을 수정합니다. 원본 집합을 보존하려면 먼저 복사본을 만드세요:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);

직접 해보기

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

class Program {
    public static HashSet<int> FindCommonElements(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 s in input1) {
                if (int.TryParse(s, out int num)) {
                    set1.Add(num);
                }
            }
        }
        
        // 두 번째 집합의 두 번째 줄 읽기
        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 s in input2) {
                if (int.TryParse(s, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        // 공통 요소 찾기
        HashSet<int> common = FindCommonElements(set1, set2);
        
        // 결과 출력 (정렬됨)
        Console.WriteLine(string.Join(" ", common.OrderBy(x => x)));
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨