Menu
CoddyTech

집하장 접수

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

접수, 무게 보고, 발송, 요금 정책의 네 단계를 연결해 소포 집하장을 만들어 보세요. Java 클래스는 소유권을 갖는 구조체와 트레이트 계약을 사용하는 Rust 모듈로 바뀝니다. 파일 구조와 변경할 수 없는 드라이버를 유지하세요. 각 후속 단계는 이전 단계의 완성된 해법에서 시작하며, 앞서 작성한 명령을 그대로 유지합니다. 이후 단계의 자리 표시자 API는 이미 컴파일되므로, 먼저 현재 계약을 구현하세요.

challenge icon

챌린지

중급

소포 보관소를 만드세요. 입력은 stage target으로 시작하고, 그 뒤에 code weight 형식의 줄이 0개 이상 이어집니다. 코드는 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단계에서는 개수를 출력하세요. 제공된 연습 코드는 네 가지 단계 명령을 모두 처리하며, 이후 단계에서 추가될 메서드는 처음에 자리표시자를 반환합니다. 현재 단계에 필요한 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();
    // PUBLIC 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);
    }

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

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

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