移植:库存命令
Coddy 面向 R 开发者的 Swift 课程的第 47 课,共 48 课。
挑战
中等将 R 参考实现移植到 Swift。实现 Inventory(),包含 add(_ name: String, count: Int) -> Bool、take(_ name: String, count: Int) -> Bool、quantity(of name: String) -> Int 和 report() -> String。add 只接受正数数量。take 只接受正数数量,且数量不能超过当前库存。拒绝操作时,所有状态保持不变;未知商品的数量为零。成功取货后,库存为零的条目仍会保留。按名称升序报告所有已存储的商品,格式为 name:quantity,各项之间用空格分隔。输入包含 0 到 40 组三元命令:add name count 或 take name count。名称为最多 10 个字母的小写 ASCII 单词,数量范围为 -10 到 100。输出成功执行的命令数;仅当报告非空时,再输出一个空格和报告内容。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印内容。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后打印返回的文本,并且恰好添加一个换行符。所有数值运算都不会超出 Int 的范围。
处理相同输入和输出约定的完整 R 参考实现:
new_inventory <- function() {
stock <- list()
quantity <- function(name) {
value <- stock[[name]]
if (is.null(value)) 0L else value
}
add <- function(name, count) {
if (count <= 0L) return(FALSE)
stock[[name]] <<- quantity(name) + count
TRUE
}
take <- function(name, count) {
available <- quantity(name)
if (count <= 0L || count > available) return(FALSE)
stock[[name]] <<- available - count
TRUE
}
report <- function() {
keys <- sort(as.character(names(stock)), method = "radix")
parts <- vapply(keys, function(name) paste0(name, ":", stock[[name]]), character(1L))
paste(parts, collapse = " ")
}
list(quantity = quantity, add = add, take = take, report = report)
}
solve <- function(tokens) {
stock <- new_inventory()
accepted <- 0L
if (length(tokens) > 0L) {
for (i in seq.int(1L, length(tokens), by = 3L)) {
name <- tokens[[i + 1L]]
count <- as.integer(tokens[[i + 2L]])
ok <- if (tokens[[i]] == "add") stock$add(name, count) else stock$take(name, count)
if (ok) accepted <- accepted + 1L
}
}
report <- stock$report()
paste0(accepted, if (nzchar(report)) paste0(" ", report) else "")
}
tokens <- scan(file("stdin"), what = character(), quiet = TRUE)
cat(solve(tokens), "\n", sep = "")你的代码写在 Inventory.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检测
let apiOK = apiChecks(input)
// 结束公开 API 检测
if apiOK { print(solve(input)) } else { print("API mismatch") }
面向 R 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器