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。它实现了相同的有效输入约定。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
static string Summarize(IEnumerable<string> rows) {
    var totals = new SortedDictionary<string,long>(StringComparer.Ordinal);
    foreach (string row in rows) {
        int space = row.IndexOf(' ');
        string name = row[..space];
        long amount = long.Parse(row[(space+1)..], CultureInfo.InvariantCulture);
        totals.TryGetValue(name, out long current);
        totals[name] = checked(current + amount);
    }
    var lines = totals.Where(pair => pair.Value > 0)
        .Select(pair => pair.Key + ":" + pair.Value.ToString(CultureInfo.InvariantCulture))
        .ToArray();
    return lines.Length == 0 ? "empty" : string.Join("\n", lines);
}
var rows = new List<string>();
string line;
while ((line = Console.ReadLine()) != null) rows.Add(line);
Console.WriteLine(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="")

面向 C# 开发者的 R 语言中的所有课

自己练习: R 在线编译器