移植:库存命令
Coddy 面向 Ruby 开发者的 Swift 课程的第 47 课,共 48 课。
挑战
中等将 Ruby 参考实现移植到 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 的范围。
相同输入和输出约定的完整 Ruby 参考实现:
class Inventory
def initialize
@stock = {}
end
def quantity(name)
@stock.fetch(name, 0)
end
def add(name, count)
return false if count <= 0
@stock[name] = quantity(name) + count
true
end
def take(name, count)
available = quantity(name)
return false if count <= 0 || count > available
@stock[name] = available - count
true
end
def report
@stock.keys.sort.map { |name| "#{name}:#{@stock[name]}" }.join(" ")
end
end
def solve(input)
stock = Inventory.new
accepted = 0
input.split.each_slice(3) do |command, name, text|
count = Integer(text)
ok = command == "add" ? stock.add(name, count) : stock.take(name, count)
accepted += 1 if ok
end
report = stock.report
accepted.to_s + (report.empty? ? "" : " " + report)
end
puts solve($stdin.read)你的代码应写在 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") }
面向 Ruby 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器