Menu
CoddyTech

집합과 멤버십

Coddy의 C 개발자를 위한 C# 코스 레슨. 48개 중 19번째.

C에는 집합 자료형이 없습니다. 중복을 허용하지 않는 기능은 직접 코드로 구현해야 합니다. 아래처럼 삽입할 때마다 배열을 훑어보면 삽입마다 한 번씩 순회해야 합니다. 또는 qsort로 정렬한 뒤 비교 결과가 같은 이웃 요소를 제거할 수 있습니다. C#의 HashSet<T>는 해시를 사용한 포함 여부 검사로 중복을 직접 방지하며, 중복 항목은 저장하지 않고 Add가 false를 반환합니다. 해시 집합은 요소를 정렬된 상태로 유지하지 않으므로, 보고서에 순서가 필요하면 명시적으로 정렬하거나 SortedSet<T>를 선택하세요.

HashSet<T>는 중복 없는 요소 관리와 빠른 포함 여부 검사를 제공합니다. 정렬된 시퀀스가 아니며, 열거 순서를 보고서의 기준으로 삼아서는 안 됩니다. 문자열의 동등성은 비교자가 결정합니다. 집합의 포함 여부와 시퀀스의 인덱스는 서로 다른 질문에 답합니다.

C 참조 코드

#include <stdio.h>
#include <string.h>

static int contains(const char **items, size_t count, const char *item) {
    for (size_t i = 0; i < count; i++)
        if (strcmp(items[i], item) == 0) return 1;
    return 0;
}

int main(void) {
    const char *input[] = { "a", "a", "b" };
    const char *seen[3];
    size_t count = 0;
    for (size_t i = 0; i < 3; i++)
        if (!contains(seen, count, input[i])) seen[count++] = input[i];
    printf("%s\n", contains(seen, count, "b") ? "yes" : "no");
    return 0;
}

Main 안의 C# 문장

var seen = new HashSet<string> { "a", "a", "b" };
Console.WriteLine(seen.Contains("b") ? "yes" : "no");

이 예제들은 핵심 내용을 설명하기 위해 발췌한 코드입니다. 과제 파일에는 실행에 필요한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.

참조 출력:

yes

C# 출력:

yes
challenge icon

챌린지

쉬움

쉼표로 구분된 비어 있지 않은 단어 목록에서 대소문자를 구분해 서로 다른 단어의 개수를 반환하세요. 빈 줄은 단어가 없음을 의미합니다.

잠금 해제된 C# 파일을 수정하세요. 표시되는 잠긴 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하며, 입력이 변경되지 않았는지 확인한 다음 마지막에 줄 바꿈을 한 번 추가해 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 인쇄하지 마세요.

직접 해보기

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Words(input[0]); string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon실력 점검

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

C 개발자를 위한 C#의 모든 레슨

직접 연습해 보세요: 온라인 C# 컴파일러