最終課題:在庫台帳
Coddyの「C++開発者のためのR」コースのレッスン 47/48。
チャレンジ
簡単summarize(rows)を実装してください。各行には、小文字のASCII文字で構成された項目名と符号付き整数の数量が、1つのスペースで区切られて記されています。名前ごとに数量を合計し、正の合計のみを残して、名前を辞書順に並べてください。名前:合計の形式の項目を改行で区切って返し、該当する項目がなければemptyを返してください。入力が空でも有効です。
宣言済みの公開APIはそのままにしてください。表示されているロック済みドライバーは、solve(lines)を出力するだけでなく、APIを直接テストします。入力は指定された契約を満たし、すべての算術演算は小さく有限です。
コードは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オンラインコンパイラ