Menu
CoddyTech

물류 센터 접수

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

연결된 4단계에 걸쳐 소화물 보관소를 구축하세요. GDScript 배열은 가변 소화물 객체에 대한 참조를 공유할 수 있지만, 이 Rust 설계는 소화물의 소유권을 직접 가지며 조회를 위해 빌려옵니다. 검증된 입고 및 중복 감지로 시작한 다음, 무게 보고, 소유권 이전을 통한 제거, 그리고 주입된 가격 책정 트레이트를 추가하세요. 각 후속 단계는 이전의 완성된 프로그램에서 시작합니다. 이후 검사에서도 이전 API를 계속 호출하므로 이전 동작과 제공된 드라이버를 그대로 유지하세요.

challenge icon

챌린지

중급

소화물 보관소를 구축하세요. 입력은 stage target으로 시작하며, 이어서 0개 이상의 code weight 줄이 옵니다. 코드는 ASCII 단어이고, 무게는 0에서 100 사이의 정수이며, 최대 20개의 행이 주어집니다. 모든 연산은 u32에 맞습니다. 유효하지 않은 소화물과 중복된 코드는 무시하고, 첫 번째 유효한 소화물만 유지합니다. Parcel::new(code: &str, weight: u32) -> Result<Parcel, &'static str>는 빈 코드나 0인 무게를 Err("invalid")로 거부하며, code(&self) -> &str 및 weight(&self) -> u32는 해당 데이터를 노출합니다. Depot::new() -> Depot는 비어 있는 상태로 시작하며, len(&self) -> usize는 소화물 개수를 셉니다. add(&mut self, parcel: Parcel) -> Result<(), &'static str>는 소유권을 가져오며, 저장된 소화물을 변경하지 않고 중복된 코드를 Err("duplicate")로 거부합니다. 단계 1에서는 개수를 출력합니다. 제공된 연습 코드는 4개의 단계 명령을 모두 디스패치하며, 이후 단계의 메서드들은 초기에 임시 값(placeholder)을 반환합니다. 현재 단계에서 요구하는 API만 구현하세요. 이후 단계에서도 이전 단계의 모든 동작을 유지하세요.

필요한 공개 API를 구현하고 마지막 줄 바꿈 없이 exercise::solve(input: &str) -> String에서 결과를 반환하세요. 수정 가능한 코드 내에서 출력하지 마세요. 잠긴 드라이버는 필요한 API를 독립적으로 검사하고, 모든 표준 입력을 읽어 반환된 텍스트를 마지막 줄 바꿈 하나와 함께 출력합니다.

코드는 exercise.rs, parcel.rs, depot.rs, policy.rs, linear.rs에 작성합니다. main.rs는 제공된 입출력 코드를 담고 있으며 편집할 수 없습니다.

직접 해보기

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod parcel;
mod depot;
mod policy;
mod linear;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // 공개 API 프로브 시작
let stage: u32 = input.split_whitespace().next().unwrap().parse().unwrap();
    use policy::Fee;
    assert_eq!(parcel::Parcel::new("", 8), Err("invalid"));
    assert_eq!(parcel::Parcel::new("bad", 0), Err("invalid"));
    let a = parcel::Parcel::new("held", 7).unwrap();
    assert_eq!(a.code(), "held"); assert_eq!(a.weight(), 7);
    let mut d = depot::Depot::new(); assert_eq!(d.len(), 0);
    assert!(d.add(a).is_ok());
    assert_eq!(d.add(parcel::Parcel::new("held", 99).unwrap()), Err("duplicate")); assert_eq!(d.len(), 1);
    d.add(parcel::Parcel::new("other", 7).unwrap()).unwrap();
    if stage >= 2 {
        assert_eq!(d.total_weight(), 14); assert_eq!(d.total_weight(), 14);
        assert_eq!(d.heaviest().unwrap().code(), "held");
        let empty = depot::Depot::new(); assert_eq!(empty.total_weight(), 0); assert!(empty.heaviest().is_none());
        let mut varied = depot::Depot::new();
        varied.add(parcel::Parcel::new("light", 3).unwrap()).unwrap();
        varied.add(parcel::Parcel::new("heavy", 19).unwrap()).unwrap();
        varied.add(parcel::Parcel::new("last", 8).unwrap()).unwrap();
        assert_eq!(varied.heaviest().unwrap().code(), "heavy"); assert_eq!(varied.total_weight(), 30);
    }
    if stage >= 3 {
        assert!(d.remove("absent").is_none()); assert_eq!(d.len(), 2); assert_eq!(d.total_weight(), 14);
        assert_eq!(d.remove("held").unwrap().weight(), 7); assert!(d.remove("held").is_none());
        assert_eq!(d.len(), 1); assert_eq!(d.heaviest().unwrap().code(), "other");
        d.add(parcel::Parcel::new("held", 2).unwrap()).unwrap(); assert_eq!(d.total_weight(), 9);
    }
    if stage >= 4 {
        struct Square;
        impl policy::Fee for Square { fn fee(&self, w: u32) -> u32 { w * w } }
        assert_eq!(linear::Linear { base: 5, rate: 2 }.fee(4), 13);
        let policy: &dyn policy::Fee = &Square;
        assert_eq!(d.quote(policy), 53); assert_eq!(d.quote(&Square), 53);
        assert_eq!(depot::Depot::new().quote(&Square), 0);
    }

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

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

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