Menu
Coddy logo textTech

Iterating Over Sets

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

HashSet을 반복하면 집합의 각 요소에 액세스할 수 있습니다. C#에서는 HashSet을 반복하는 다양한 방법을 사용할 수 있습니다.

foreach 루프 사용:

// Create a HashSet
HashSet<string> colors = new HashSet<string>();

// Add elements to the HashSet
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

// Iterate through the HashSet
foreach (string color in colors)
{
    Console.WriteLine(color);
}

HashSet은 삽입 순서를 유지하지 않으므로, 요소들은 추가된 순서와 동일하게 반복되지 않을 수 있습니다.

또는 먼저 배열이나 리스트로 변환할 수도 있습니다:

// Convert to array and iterate
string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
    Console.WriteLine(colorArray[i]);
}
challenge icon

챌린지

쉬움

PrintSetElements라는 메서드를 만드세요. 이 메서드는 정수의 HashSet을 입력으로 받아 세트를 반복하면서 각 요소를 새 줄에 출력해야 합니다.

예를 들어, 세트가 [5, 2, 8]을 포함하면 메서드는 다음과 같이 출력해야 합니다:

5 2 8

치트 시트

C#에서 HashSet을 반복하려면 foreach 루프를 사용하세요:

HashSet<string> colors = new HashSet<string>();
colors.Add("Red");
colors.Add("Green");
colors.Add("Blue");

foreach (string color in colors)
{
    Console.WriteLine(color);
}

HashSet은 삽입 순서를 유지하지 않으므로 요소는 추가된 순서와 동일하게 반복되지 않을 수 있습니다.

또는 먼저 배열로 변환할 수도 있습니다:

string[] colorArray = colors.ToArray();
for (int i = 0; i < colorArray.Length; i++)
{
    Console.WriteLine(colorArray[i]);
}

직접 해보기

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

class Program
{
    public static void PrintSetElements(HashSet<int> set)
    {
        // 여기에 코드를 작성하세요
    }
    
    static void Main(string[] args)
    {
        HashSet<int> numbers = new HashSet<int>();
        
        // 형식을 확인하기 위해 첫 번째 줄 읽기
        string firstLine = Console.ReadLine();
        
        // 입력이 JSON 배열 형식인지 확인
        if (firstLine != null && firstLine.StartsWith("[") && firstLine.EndsWith("]"))
        {
            try
            {
                // 대괄호 사이의 내용 추출
                string arrayContent = firstLine.Substring(1, firstLine.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))
                    {
                        numbers.Add(num);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing JSON input: {ex.Message}");
                return;
            }
        }
        else
        {
            try
            {
                // 전통 형식 - 개수 읽은 후 요소들 읽기
                int count = int.Parse(firstLine);
                
                // 각 요소를 읽어 세트에 추가
                for (int i = 0; i < count; i++)
                {
                    int num = int.Parse(Console.ReadLine());
                    numbers.Add(num);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing traditional input: {ex.Message}");
                return;
            }
        }
        
        PrintSetElements(numbers);
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨