Menu
Coddy logo textTech

Math - Set Difference

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

집합 차집합 연산은 첫 번째 집합에 존재하지만 두 번째 집합에는 존재하지 않는 요소들로 구성된 새로운 집합을 생성합니다.

두 개의 HashSet을 생성하세요:

HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();

두 세트에 요소를 추가하세요:

set1.Add("Apple");
set1.Add("Banana");
set1.Add("Cherry");

set2.Add("Banana");
set2.Add("Kiwi");

차집합 계산(set1에 있지만 set2에는 없는 요소들):

HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);

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

["Apple", "Cherry"]
challenge icon

챌린지

쉬움

GetSetDifference라는 이름을 가진 메서드를 생성하세요. 이 메서드는 정수의 HashSet 두 개(set1set2)를 매개변수로 받아 set1에 있지만 set2에는 없는 요소들로 구성된 집합 차집합(새로운 HashSet)을 반환해야 합니다.

치트 시트

집합 차집합은 첫 번째 집합에 존재하지만 두 번째 집합에는 존재하지 않는 요소들로 새로운 집합을 생성합니다.

HashSet 생성:

HashSet<string> set1 = new HashSet<string>();
HashSet<string> set2 = new HashSet<string>();

ExceptWith()을 사용하여 차집합 계산:

HashSet<string> difference = new HashSet<string>(set1);
difference.ExceptWith(set2);

직접 해보기

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

class Program {
    public static HashSet<int> GetSetDifference(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[] set1Input = line1.Split(' ');
            foreach (string item in set1Input) {
                if (int.TryParse(item, 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[] set2Input = line2.Split(' ');
            foreach (string item in set2Input) {
                if (int.TryParse(item, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        HashSet<int> difference = GetSetDifference(set1, set2);
        
        // 결과 출력
        List<int> sortedResult = new List<int>(difference);
        sortedResult.Sort();
        foreach (int item in sortedResult) {
            Console.WriteLine(item);
        }
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨