Menu
CoddyTech

最终挑战:股票账本

Coddy 面向 C++ 开发者的 R 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

实现 summarize(rows)。每一行由一个小写 ASCII 项目名称和一个有符号整数数量组成,两者之间用一个空格分隔。按名称汇总数量;只保留正数总和;按字典顺序对名称排序;返回以换行符分隔的 name:total 条目,如果没有则返回 empty。允许输入为空。

保留已声明的公共 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 在线编译器