맵과 셋
Coddy의 C# 개발자를 위한 Rust 코스 레슨. 48개 중 23번째.
C# 사전과 Rust 맵은 키를 값에 연결하지만, 열거 순서는 명시적인 계약에 따라야 합니다. Rust의 BTreeMap과 BTreeSet은 정렬된 키 순서로 순회할 수 있지만, HashMap과 HashSet은 안정적으로 정렬된 순서를 보장하지 않습니다. 예제에서는 순서가 있는 집합을 사용해 이미 알고 있는 태그를 제거한 다음 나머지 항목을 순회합니다. 여기서는 ASCII 정렬 의도를 명확히 하기 위해 C#의 SortedSet<string>에 서수 비교자를 지정하며, 문화권에 의존하지 않습니다. Rust의 BTreeSet<&str>은 문자열 정렬 구현을 사용합니다. 집합은 고유한 요소를 저장하며, 제거에 실패하면 변경되지 않습니다. Rust에서 맵을 조회하면 일반적으로 Option<&V>가 반환되므로 키가 없을 때 예외 없이 표현할 수 있습니다. 이는 예외를 던지는 C# 사전 인덱서와 다릅니다. TryGetValue가 부재를 명시적으로 처리하는 데 더 가깝습니다. 프로그램 출력을 결정적으로 만들려면 순서가 있는 컬렉션을 선택하거나 출력을 명시적으로 정렬하세요.
완전한 C# 프로그램:
using System;
using System.Collections.Generic;
class Program {
static void Main() {
var tags = new SortedSet<string>(StringComparer.Ordinal) { "z", "a", "m" };
tags.Remove("m");
foreach (string tag in tags) Console.WriteLine(tag);
}
}완전한 Rust 프로그램:
use std::collections::BTreeSet;
fn main() {
let mut tags = BTreeSet::new();
tags.insert("z"); tags.insert("a"); tags.insert("m");
tags.remove("m");
for tag in &tags { println!("{}", tag); }
}챌린지
쉬움pub fn frequencies(text: &str) -> BTreeMap<String, usize>와 pub fn repeated(text: &str) -> BTreeSet<String>를 vocabulary.rs에 구현하고, 두 자료형을 모두 std::collections에서 가져오세요. 공백을 기준으로 텍스트를 나누고, 대소문자를 구분해 단어를 비교하며 문장 부호는 유지하세요. frequencies는 모든 출현 횟수를 셉니다. repeated에는 횟수가 2회 이상인 단어만 포함됩니다. solve는 반복된 단어를 정렬된 순서로 word=count 형식으로 반환하고, 쉼표로 구분합니다. 집합이 비어 있으면 none을 반환하세요. 두 API 모두 빈 입력과 전역 상태를 유지하지 않는 독립적인 호출을 처리해야 합니다.
필수로 내보내야 하는 API를 구현하고, 마지막 개행 없이 exercise::solve(input: &str) -> String의 결과를 반환하세요. 편집 가능한 코드에서 출력하지 마세요. 잠긴 드라이버는 필수 API를 각각 별도로 확인하고, 표준 입력을 모두 읽은 뒤 반환된 텍스트를 마지막 개행 하나와 함께 출력합니다.
코드는 exercise.rs와 vocabulary.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod vocabulary;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
let counts = vocabulary::frequencies("fern oak fern elm oak fern");
assert_eq!(counts.len(), 3);
assert_eq!(counts.get("fern"), Some(&3));
assert_eq!(counts.get("elm"), Some(&1));
assert_eq!(counts.get("missing"), None);
let repeated = vocabulary::repeated("fern oak fern elm oak fern");
assert_eq!(repeated.into_iter().collect::<Vec<_>>(), vec![String::from("fern"), String::from("oak")]);
assert!(vocabulary::frequencies("").is_empty());
assert!(vocabulary::repeated("single").is_empty());
assert_eq!(vocabulary::frequencies("A a").len(), 2);
// PUBLIC API 검사 종료
println!("{}", exercise::solve(&input));
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C# 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러