Menu
CoddyTech

동등성과 해싱

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

C#의 HashSet은 오버로드된 == 연산자를 단순히 호출하는 대신 EqualityComparer를 사용합니다. Dart의 해시 컬렉션은 ==와 hashCode에 의존합니다. 두 경우 모두 같은 객체는 일관된 해시 값과 안정적인 동등성 필드가 필요합니다.

같은 객체는 hashCode 값도 같아야 하지만, 해시 충돌이 동등성을 증명하지는 않습니다. 객체가 해시 컬렉션에 저장되어 있는 동안 동등성 판단에 영향을 주는 상태를 안정적으로 유지하세요.

완전한 C# 프로그램:

using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Tag{readonly string text;public Tag(string text){this.text=text;}public override bool Equals(object other){return other is Tag && text==((Tag)other).text;}public override int GetHashCode(){return text.GetHashCode();}}
static void Main(){Console.WriteLine(new HashSet<Tag>{new Tag("a"),new Tag("a")}.Count);}
}

완전한 Dart 프로그램:

class Tag{final String text;const Tag(this.text);@override bool operator ==(Object other)=>other is Tag&&text==other.text;@override int get hashCode=>text.hashCode;}
void main(){print({Tag('a'),Tag('a')}.length);}
challenge icon

챌린지

쉬움

final 공개 필드를 가진 불변 Key(int row,int column)를 구현하세요. 두 Key는 두 좌표가 모두 일치할 때만 같습니다. operator ==와 hashCode를 일관성 있게 재정의하세요. 입력은 완전한 정수 좌표 쌍으로 이루어집니다. Set을 사용해 서로 다른 키의 개수를 세고 그 개수를 반환하세요. 좌표 범위는 -100부터 100까지입니다.

편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 파싱하고 출력을 반환합니다. 잠금된 드라이버는 공개 API를 별도로 테스트하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.

코드는 Key.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.

직접 해보기

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Key.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final a=Key(2,3),b=Key(2,3);check(a==b && a.hashCode==b.hashCode && a!=Key(3,2));check({a,b}.length==1);
stdout.writeln(solve(input));
}
quiz icon실력 점검

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

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

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