最终挑战:库存账本
Coddy 面向 Dart 开发者的 R 课程的第 47 课,共 48 课。
挑战
简单实现 summarize(rows)。每一行包含一个小写 ASCII 项目名称和一个有符号整数金额,两者由一个空格分隔。按名称汇总金额;只保留正数总额;按字典序排列名称;返回以换行符分隔的 name:total 条目,如果没有条目,则返回 empty。允许输入为空。
保留已声明的公共 API。可见的锁定驱动程序会直接检查它,也会打印 solve(lines)。输入符合上述约定;所有运算都很小且有限。
你的代码写在 Functions.R 和 Exercise.R 中。main.R 按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑该文件。
将这段完整的 Dart 参考代码移植到 R 公共 API 中。它实现了相同的有效输入约定。
import 'dart:io';
String summarize(Iterable<String> rows) {
final totals=<String,int>{};
for(final row in rows) {
final space=row.indexOf(' ');
final name=row.substring(0,space);
final amount=int.parse(row.substring(space+1));
totals[name]=(totals[name] ?? 0)+amount;
}
final names=totals.keys.where((name)=>totals[name]!>0).toList()..sort();
return names.isEmpty ? 'empty' : names.map((name)=>name+':'+totals[name].toString()).join('\n');
}
void main() {
final rows=<String>[];
String? line;
while((line=stdin.readLineSync())!=null) {
rows.add(line!);
}
print(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="")
面向 Dart 开发者的 R中的所有课
自己练习: R 在线编译器