移植:在庫コマンド
Coddyの「C++開発者のためのSwift」コースのレッスン 47/48。
チャレンジ
中級C++の参照実装をSwiftに移植してください。add(_ name: String, count: Int) -> Bool、take(_ name: String, count: Int) -> Bool、quantity(of name: String) -> Int、report() -> Stringを備えたInventory()を実装してください。addが受け付けるのは正の個数だけです。takeが受け付けるのは、正の個数で、現在の在庫以下の場合だけです。拒否された場合は状態を一切変更しません。不明な品目の数量は0です。正常にtakeされた後も、在庫が0になった品目を保持します。保存されているすべての品目名を昇順で、name:quantityの形式で空白区切りにしてreportしてください。入力には0〜40個のコマンドトリプルが含まれます。形式はadd name countまたはtake name countです。品目名は小文字のASCII単語で、長さは最大10文字です。個数は-10〜100です。出力は成功したコマンドの数と、reportが空でない場合に限り、その後に空白とreportを続けたものです。
必要なAPIとsolve(_ input: String) -> Stringを実装してください。末尾に改行を付けずに出力テキストを返してください。編集可能なコード内では出力しないでください。ロックされたドライバーは、追加の有効な入力を使ってAPIを個別に確認してから、返されたテキストをちょうど1つの改行付きで出力します。すべての数値演算はIntの範囲内に収まります。
C++の参照実装では、クラス値の内部に順序付きマップを保持しています。その値への参照は状態を共有しますが、マップを保持するオブジェクトをコピーすると独立した値が作られます。Swiftの実装でも、拒否時に変更しないことと、在庫が0の品目を保持することを維持してください。
以下は、指定された入力/出力の仕様を満たすC++の完全な参照実装です。この動作を必要なSwiftファイルに移植してください。
#include <iostream>
#include <string>
#include <map>
#include <sstream>
class Inventory {
std::map<std::string, int> quantities;
public:
int quantity(const std::string &name) const {
auto found = quantities.find(name);
return found == quantities.end() ? 0 : found->second;
}
bool add(const std::string &name, int count) {
if (count <= 0) return false;
quantities[name] = quantity(name) + count;
return true;
}
bool take(const std::string &name, int count) {
int available = quantity(name);
if (count <= 0 || count > available) return false;
quantities[name] = available - count;
return true;
}
std::string report() const {
std::ostringstream output;
bool first = true;
for (const auto &[name, value] : quantities) {
if (!first) output << ' ';
first = false;
output << name << ':' << value;
}
return output.str();
}
};
int main() {
Inventory inventory;
std::string command, name;
int count, accepted = 0;
while (std::cin >> command >> name >> count) {
bool ok = command == "add" ? inventory.add(name, count) : inventory.take(name, count);
if (ok) ++accepted;
}
std::string report = inventory.report();
std::cout << accepted;
if (!report.empty()) std::cout << ' ' << report;
std::cout << '\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") }
C++開発者のためのSwiftのすべてのレッスン
自分で練習してみよう: Swiftプレイグラウンド