Menu
CoddyTech

최종: 재고 장부

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

challenge icon

챌린지

쉬움

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

선언된 공개 API를 유지하세요. 화면에 보이는 잠금된 드라이버는 API를 직접 검사하고 solve(lines)도 출력합니다. 입력은 명시된 조건을 만족하며, 모든 산술 연산은 작은 유한값입니다.

코드는 Functions.R과 Exercise.R에 작성하세요. main.R은 의존 파일을 순서대로 불러오고 제공된 입출력 코드를 포함하며, 수정할 수 없습니다.

이 완전한 C++ 참조 코드를 R 공개 API로 포팅하세요. 이 코드는 동일한 유효 입력 조건을 구현합니다.

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::string summarize(const std::vector<std::string>& rows) {
    std::map<std::string,long long> totals;
    for (const auto& row : rows) {
        std::istringstream input(row);
        std::string name;
        long long amount;
        input >> name >> amount;
        totals[name] += amount;
    }
    std::ostringstream result;
    bool found=false;
    for (const auto& entry : totals) if (entry.second>0) {
        if (found) result << '\n';
        result << entry.first << ':' << entry.second;
        found=true;
    }
    return found ? result.str() : "empty";
}
int main() {
    std::vector<std::string> rows;
    std::string line;
    while (std::getline(std::cin,line)) rows.push_back(line);
    std::cout << summarize(rows) << '\n';
}

직접 해보기

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="")

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

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