Menu
CoddyTech

最终挑战:库存账簿

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

challenge icon

挑战

简单

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

保留已声明的公共 API。可见的锁定驱动程序会直接检查它,并打印 solve(lines)。输入符合上述约定;所有算术运算的数值都很小且有限。

你的代码应写在 Functions.R 和 Exercise.R 中。main.R 会按顺序加载依赖项,并包含提供的输入/输出代码;不能编辑该文件。

将这份完整的 GDScript 参考实现移植到 R 的公共 API 中。它实现了相同的有效输入约定。

extends SceneTree

func summarize(rows: Array) -> String:
    var totals = {}
    for row in rows:
        var space = row.find(" ")
        var item_name = row.substr(0, space)
        var amount = int(row.substr(space + 1))
        totals[item_name] = totals.get(item_name, 0) + amount
    var names = totals.keys()
    names.sort()
    var lines = PackedStringArray()
    for item_name in names:
        if totals[item_name] > 0:
            lines.append(item_name + ":" + str(totals[item_name]))
    return "empty" if lines.is_empty() else "\n".join(lines)

func _init():
    var rows = []
    while true:
        var line = OS.read_string_from_stdin()
        # A valid row is nonempty; an empty read marks the end of input.
        if line.is_empty():
            break
        rows.append(line.trim_suffix("\n").trim_suffix("\r"))
    print(summarize(rows))
    quit()

亲手试试

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

面向 GDScript 开发者的 R中的所有课

自己练习: R 在线编译器