Menu
CoddyTech

최종: 재고 원장

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

challenge icon

챌린지

쉬움

summarize(rows)를 구현하세요. 각 행은 소문자 ASCII 항목 이름과 부호가 있는 정수 수량이 공백 하나로 구분된 형태입니다. 이름별로 수량을 합산하고, 양수인 합계만 유지한 다음, 이름을 사전순으로 정렬하세요. 이름:합계 항목들을 줄바꿈으로 구분해 반환하고, 해당 항목이 없으면 empty를 반환하세요. 입력이 비어 있어도 유효합니다.

선언된 공개 API를 유지하세요. 화면에 보이는 잠긴 드라이버는 solve(lines)를 출력할 뿐 아니라 API를 직접 검사합니다. 입력은 명시된 계약을 따르며, 모든 산술 연산은 작은 유한 값입니다.

코드는 Functions.R와 Exercise.R에 작성하세요. main.R은 종속성을 순서대로 불러오고 제공된 입력/출력 코드를 포함합니다. 이 파일은 수정할 수 없습니다.

이 완전한 Rust 참조 구현을 R 공개 API로 이식하세요. 동일한 유효 입력 계약을 구현합니다.

use std::collections::BTreeMap;
use std::io::{self, Read};
fn summarize(rows: &[&str]) -> String {
    let mut totals: BTreeMap<&str, i64> = BTreeMap::new();
    for row in rows {
        let (name, amount) = row.split_once(' ').unwrap();
        let amount: i64 = amount.parse().unwrap();
        let total = totals.entry(name).or_insert(0);
        *total = total.checked_add(amount).unwrap();
    }
    let lines: Vec<String> = totals.into_iter()
        .filter(|(_, total)| *total > 0)
        .map(|(name, total)| format!("{}:{}", name, total))
        .collect();
    if lines.is_empty() { "empty".into() } else { lines.join("\n") }
}
fn main() {
    let mut text = String::new();
    io::stdin().read_to_string(&mut text).unwrap();
    let rows: Vec<&str> = text.lines().collect();
    println!("{}", summarize(&rows));
}

직접 해보기

source("Functions.R")
source("Exercise.R")
stopifnot(identical(summarize(c("q 9","q -2","b 1")),"b:1\nq:7"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")

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

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