Menu
CoddyTech

移植:库存命令

Coddy 面向 Kotlin 开发者的 Swift 课程的第 47 课,共 48 课。

challenge icon

挑战

中等

将 Kotlin 参考实现移植到 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 的范围内。

相同输入和输出约定的完整 Kotlin 参考实现:

class Inventory {
    private val stock = mutableMapOf<String, Int>()
    fun add(name: String, count: Int): Boolean {
        if (count <= 0) return false
        stock[name] = (stock[name] ?: 0) + count
        return true
    }
    fun take(name: String, count: Int): Boolean {
        val old = stock[name] ?: 0
        if (count <= 0 || count > old) return false
        stock[name] = old - count
        return true
    }
    fun report(): String = stock.keys.sorted().joinToString(" ") { "$it:${stock[it]}" }
}
fun main() {
    val inventory = Inventory()
    val tokens = generateSequence(::readLine).joinToString(" ").trim()
    val p = if (tokens.isEmpty()) emptyList() else tokens.split(Regex("""\s+"""))
    var accepted = 0
    for (i in p.indices step 3) {
        val ok = if (p[i] == "add") inventory.add(p[i+1], p[i+2].toInt())
                 else inventory.take(p[i+1], p[i+2].toInt())
        if (ok) accepted++
    }
    val report = inventory.report()
    println(accepted.toString() + if (report.isEmpty()) "" else " " + report)
}

你的代码应写在 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") }

面向 Kotlin 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器