Menu
CoddyTech

移植:库存命令

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

challenge icon

挑战

中等

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

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

<?php
declare(strict_types=1);
final class Inventory {
    private array $stock = [];
    public function quantity(string $name): int { return $this->stock[$name] ?? 0; }
    public function add(string $name, int $count): bool {
        if ($count <= 0) return false;
        $this->stock[$name] = $this->quantity($name) + $count;
        return true;
    }
    public function take(string $name, int $count): bool {
        $available = $this->quantity($name);
        if ($count <= 0 || $count > $available) return false;
        $this->stock[$name] = $available - $count;
        return true;
    }
    public function report(): string {
        $sorted = $this->stock;
        ksort($sorted, SORT_STRING);
        $parts = [];
        foreach ($sorted as $name => $quantity) $parts[] = "$name:$quantity";
        return implode(" ", $parts);
    }
}
function solve(string $input): string {
    $tokens = preg_split('/\s+/', trim($input), -1, PREG_SPLIT_NO_EMPTY);
    $stock = new Inventory();
    $accepted = 0;
    for ($i = 0; $i < count($tokens); $i += 3) {
        $name = $tokens[$i + 1];
        $count = (int)$tokens[$i + 2];
        $ok = $tokens[$i] === "add" ? $stock->add($name, $count) : $stock->take($name, $count);
        if ($ok) $accepted++;
    }
    $report = $stock->report();
    return (string)$accepted . ($report === "" ? "" : " " . $report);
}
echo solve(stream_get_contents(STDIN)), "\n";

将代码写入 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") }

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

自己练习: Swift 在线编辑器