수학 - 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);챌린지
중급두 개의 인수를 받는 FindCommonElements라는 메서드를 만드세요.
- 정수로 이루어진 HashSet (set1)
- 정수로 이루어진 HashSet (set2)
이 메서드는 두 집합에 모두 포함된 요소(교집합)만 담은 새 HashSet을 반환해야 합니다.
직접 해보기
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)));
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러