Menu
CoddyTech

包裹发送

Coddy 面向 C++ 开发者的 Swift 课程 课程的第 45 课,共 48 课。

challenge icon

挑战

中等

保留入库和报告功能。完成 dispatch(_ id: String) -> Parcel?:移除并返回匹配的包裹,如果不存在则返回 nil 且不作任何更改。数量和重量必须反映出移除后的变化。所有四个阶段均使用相同的文件和驱动程序。Parcel(id:weight:) 是值类型,而 ParcelDesk() 是引用类型。输入以此阶段编号 3 开头,后跟 0 到 30 个 ID/重量对。ID 为 1 到 10 个 ASCII 小写字母,重量为 0 到 100。忽略重复的 ID。派发第一个输入 ID(如果有)。输出其被移除的重量(如果不存在则为 0),接着是一个空格,然后是剩余的数量。阶段尚未涉及的方法在到达对应阶段前保持占位状态。

实现所需的 API 和 solve(_ input: String) -> String。返回输出文本,末尾不带换行符;不要在可编辑的代码中打印。锁定状态的驱动程序会使用其他有效输入独立检查 API,然后打印返回的文本,末尾恰好带有一个换行符。所有数值运算均保持在 Int 范围内。

你的代码应编写在 Parcel.swift、PricePolicy.swift、UnitPrice.swift、ParcelDesk.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,无法编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
struct ProbePrice: PricePolicy { func cost(weight: Int) -> Int { weight + 11 } }
let p = input.split(whereSeparator: { $0.isWhitespace }); let stage = Int(p[0])!
let d = ParcelDesk()
guard d.add(Parcel(id: "p", weight: 7)), !d.add(Parcel(id: "p", weight: 9)), d.add(Parcel(id: "q", weight: 2)), d.count == 2 else { return false }
if stage >= 2 { guard d.totalWeight == 9 else { return false } }
if stage >= 3 { guard d.dispatch("missing") == nil && d.count == 2 else { return false }; guard d.dispatch("p")?.weight == 7 && d.count == 1 && d.totalWeight == 2 && d.dispatch("p") == nil else { return false } }
if stage >= 4 { guard UnitPrice(rate: 5).cost(weight: 4) == 20 && d.quote(using: ProbePrice()) == 13 && d.quote(using: UnitPrice(rate: 4)) == 8 else { return false } }
return true
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 公共 API 探针开始
let apiOK = apiChecks(input)
// 公共 API 探针结束
if apiOK { print(solve(input)) } else { print("API mismatch") }

面向 C++ 开发者的 Swift 课程中的所有课

自己练习: Swift 在线编辑器