Menu
CoddyTech

컬렉션 복습

Coddy의 Python 개발자를 위한 Rust 코스 레슨. 48개 중 24번째.

challenge icon

챌린지

쉬움

pub fn add(stock: &mut BTreeMap<String, usize>, name: &str)와 pub fn remove(stock: &mut BTreeMap<String, usize>, name: &str) -> bool를 stock.rs에 구현하세요. Add는 이름의 개수를 늘리고, 해당 이름이 없으면 개수를 1로 설정해 추가합니다. Remove는 해당 이름이 없으면 아무것도 변경하지 않고 false를 반환합니다. 이름이 있으면 개수를 줄이고 true를 반환하며, 개수가 0이 되면 키를 제거합니다. 유효한 재고 맵에는 양수인 개수만 포함됩니다. 입력은 0개 이상의 줄로 이루어지며 각 줄은 +name 또는 -name입니다. 이름은 비어 있지 않고 공백을 포함하지 않으며 유니코드를 포함할 수 있습니다. solve는 빈 재고로 시작해 명령을 순서대로 적용하고 removed|entries를 반환합니다. 여기서 removed는 성공적으로 제거된 횟수이고, entries는 쉼표로 연결된 정렬된 name=count 쌍입니다. 항목이 없으면 empty를 사용하세요.

필수로 내보내야 하는 API를 구현하고, 마지막 줄바꿈 없이 exercise::solve(input: &str) -> String의 결과를 반환하세요. 편집 가능한 코드에서는 출력하지 마세요. 잠긴 드라이버는 필수 API를 각각 검사하고, stdin 전체를 읽은 다음 반환된 텍스트를 마지막 줄바꿈 하나와 함께 출력합니다.

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

직접 해보기

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 공개 API 검사 시작
let mut items = std::collections::BTreeMap::new();
stock::add(&mut items, "bolt"); stock::add(&mut items, "bolt");
stock::add(&mut items, "nut");
let unchanged = items.clone();
assert!(!stock::remove(&mut items, "absent"));
assert_eq!(items, unchanged);
assert!(stock::remove(&mut items, "bolt"));
assert_eq!(items.get("bolt"), Some(&1));
assert!(stock::remove(&mut items, "bolt"));
assert!(!items.contains_key("bolt"));
assert!(!stock::remove(&mut items, "bolt"));
assert_eq!(items.get("nut"), Some(&1));

    // 공개 API 검사 종료
    println!("{}", exercise::solve(&input));
}

Python 개발자를 위한 Rust의 모든 레슨

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