최종: 재고 장부
Coddy의 R 개발자를 위한 Rust 코스 레슨. 48개 중 47번째.
챌린지
중급완전한 R 참조 구현을 제공된 Rust API로 포팅하세요. R의 상태 반환값은 명시적인 Rust Result 값이 되고, 환경에 저장된 재고 클로저는 소유된 Rust 상태가 됩니다. 입력에는 최대 100개의 name delta 행이 있으며, 이름은 최대 31바이트의 소문자 ASCII 단어이고 증감량은 -1000부터 1000까지입니다. 빈 입력도 유효합니다. Stock::new() -> Stock은 0에서 시작하고, quantity(&self) -> i32는 수량을 읽으며, apply(&mut self, delta: i32) -> Result<(), &'static str>는 결과 수량이 음수가 되면 Err("negative")를 반환하고 상태를 변경하지 않습니다. Ledger::new() -> Ledger는 빈 상태에서 시작합니다. apply(&mut self, name: &str, delta: i32)도 같은 반환 규약을 따르며, 거부할 때 존재하지 않는 항목을 생성해서는 안 됩니다. quantity(&self, name: &str) -> Option<i32>는 항목이 없을 때와 수량이 0일 때를 구분합니다. report(&self) -> String는 이름순으로 양수 재고만 name:quantity 형식으로 나열하고, 각 항목은 줄바꿈으로 구분하며, 항목이 없으면 empty를 반환합니다. rejected:N을 반환한 뒤 다음 줄들에 보고서를 출력하세요. report 호출은 상태를 변경하지 않습니다. R 환경은 변경 가능한 캡처 수량을 가진 재고 클로저를 저장합니다. Rust에서는 맵에 이름과 재고 값을 소유해야 합니다. 항목이 없는 경우와 수량이 0인 항목을 구분해야 합니다.
필수로 내보내야 하는 API를 구현하고, 최종 줄바꿈 없이 exercise::solve(input: &str) -> String의 결과를 반환하세요. 편집 가능한 코드에서 출력하지 마세요. 잠긴 드라이버는 필수 API를 각각 독립적으로 검사하고, stdin 전체를 읽은 다음 반환된 텍스트를 마지막 줄바꿈 하나와 함께 출력합니다.
코드는 exercise.rs, stock.rs, ledger.rs에 작성하세요. main.rs에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.
동일한 유효 입력 규약을 위한 완전한 R 참조 구현:
new_stock <- function() {
amount <- 0
list(quantity = function() amount,
apply = function(delta) {
candidate <- amount + delta
if (candidate < 0) return(FALSE)
amount <<- candidate
TRUE
})
}
new_ledger <- function() {
entries <- new.env(hash = TRUE, parent = emptyenv())
list(apply = function(name, delta) {
present <- exists(name, envir = entries, inherits = FALSE)
stock <- if (present) get(name, envir = entries, inherits = FALSE) else new_stock()
if (!stock$apply(delta)) return(FALSE)
if (!present) assign(name, stock, envir = entries)
TRUE
},
quantity = function(name) {
if (!exists(name, envir = entries, inherits = FALSE)) return(NULL)
get(name, envir = entries, inherits = FALSE)$quantity()
},
report = function() {
names <- sort(ls(entries, all.names = TRUE), method = "radix")
rows <- character()
for (name in names) {
amount <- get(name, envir = entries, inherits = FALSE)$quantity()
if (amount > 0) rows <- c(rows, paste0(name, ":", sprintf("%.0f", amount)))
}
if (length(rows) == 0L) "empty" else paste(rows, collapse = "\n")
})
}
text <- trimws(paste(readLines(file("stdin"), warn = FALSE), collapse = "\n"))
words <- if (nchar(text) == 0L) character() else strsplit(text, "[[:space:]]+")[[1L]]
ledger <- new_ledger()
rejected <- 0L
if (length(words) > 0L) {
for (index in seq.int(1L, length(words), by = 2L)) {
if (!ledger$apply(words[index], as.numeric(words[index + 1L]))) rejected <- rejected + 1L
}
}
cat("rejected:", rejected, "\n", ledger$report(), "\n", sep = "")
직접 해보기
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// PUBLIC API 검사 시작
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
assert_eq!(ledger::Ledger::new().report(), "empty");
// PUBLIC API 검사 종료
println!("{}", exercise::solve(&input));
}
R 개발자를 위한 Rust의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러