Menu
CoddyTech

移植:库存命令

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

challenge icon

挑战

中等

将 Rust 参考实现移植到 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。名称为小写 ASCII 单词,长度最多为 10 个字母;数量范围为 -10 到 100。输出成功执行的命令数;仅当报告不为空时,再在其后输出一个空格和报告内容。

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

同一输入和输出约定的完整 Rust 参考实现:

use std::collections::BTreeMap;
use std::io::{self, Read};
#[derive(Default)]
struct Inventory { stock: BTreeMap<String, i64> }
impl Inventory {
    fn quantity(&self, name: &str) -> i64 { self.stock.get(name).copied().unwrap_or(0) }
    fn add(&mut self, name: &str, count: i64) -> bool {
        if count <= 0 { return false; }
        let next = self.quantity(name) + count;
        self.stock.insert(name.to_owned(), next);
        true
    }
    fn take(&mut self, name: &str, count: i64) -> bool {
        let available = self.quantity(name);
        if count <= 0 || count > available { return false; }
        self.stock.insert(name.to_owned(), available - count);
        true
    }
    fn report(&self) -> String {
        self.stock.iter().map(|(name, count)| format!("{}:{}", name, count))
            .collect::<Vec<_>>().join(" ")
    }
}
fn solve(input: &str) -> String {
    let tokens: Vec<&str> = input.split_whitespace().collect();
    let mut stock = Inventory::default();
    let mut accepted = 0;
    for command in tokens.chunks_exact(3) {
        let count: i64 = command[2].parse().unwrap();
        let ok = if command[0] == "add" { stock.add(command[1], count) }
                 else { stock.take(command[1], count) };
        if ok { accepted += 1; }
    }
    let report = stock.report();
    if report.is_empty() { accepted.to_string() } else { format!("{} {}", accepted, report) }
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    println!("{}", solve(&input));
}

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

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

自己练习: Swift 在线编辑器