移植:インベントリコマンド
Coddyの「C開発者のためのSwift」コースのレッスン 47/48。
チャレンジ
中級Cの参照実装をSwiftに移植してください。Inventory()を実装し、add(_ name: String, count: Int) -> Bool、take(_ name: String, count: Int) -> Bool、quantity(of name: String) -> Int、およびreport() -> Stringを用意してください。Addが受け付けるのは正の個数のみです。Takeが受け付けるのは、正で現在の在庫以下の個数のみです。拒否された場合は状態を一切変更しません。不明な品目の数量は0です。成功したtakeの後も、在庫が0になった項目は保持します。保存されているすべての名前を昇順に並べ、name:quantityの形式で空白区切りにして報告します。入力には0〜40個のコマンドトリプルが含まれます。形式はadd name countまたはtake name countです。名前は最大10文字の小文字ASCII単語、個数は-10〜100です。成功したコマンド数を出力し、報告が空でない場合に限り、その後に空白と報告を続けてください。
必要なAPIとsolve(_ input: String) -> Stringを実装してください。最後に改行を付けずに出力テキストを返し、編集可能なコード内では出力しないでください。ロックされたドライバーは追加の有効な入力でAPIを個別に検査した後、返されたテキストを改行1つだけ付けて出力します。すべての数値演算はIntの範囲内に収まります。
CのInventoryは、上限付きの項目を内部に格納し、ポインターを通じて元のデータを更新します。報告用には一時配列をソートし、保存状態は変更しません。必要なSwiftの参照型APIと、コマンドが拒否された後のすべての状態を保持してください。
Cの参照プログラム全体です。隣にあるinventory.hとともにmain.cをコンパイルしてください。このヘッダーには、唯一のエントリーポイントから使用される実装が含まれています。この最終移植用に、実装は意図的に完成した状態になっています。
inventory.h
#ifndef INVENTORY_H
#define INVENTORY_H
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct { char name[11]; int quantity; } Item;
typedef struct { Item items[40]; int size; } Inventory;
static int inventory_find(const Inventory *inventory, const char *name) {
for (int i = 0; i < inventory->size; ++i)
if (strcmp(inventory->items[i].name, name) == 0) return i;
return -1;
}
static int inventory_quantity(const Inventory *inventory, const char *name) {
int index = inventory_find(inventory, name);
return index < 0 ? 0 : inventory->items[index].quantity;
}
static bool inventory_add(Inventory *inventory, const char *name, int count) {
if (count <= 0) return false;
int index = inventory_find(inventory, name);
if (index < 0) {
index = inventory->size++;
strcpy(inventory->items[index].name, name);
inventory->items[index].quantity = 0;
}
inventory->items[index].quantity += count;
return true;
}
static bool inventory_take(Inventory *inventory, const char *name, int count) {
int available = inventory_quantity(inventory, name);
if (count <= 0 || count > available) return false;
inventory->items[inventory_find(inventory, name)].quantity = available - count;
return true;
}
static int item_compare(const void *left, const void *right) {
return strcmp(((const Item *)left)->name, ((const Item *)right)->name);
}
static void inventory_report(const Inventory *inventory, char output[1024]) {
Item sorted[40];
memcpy(sorted, inventory->items, (size_t)inventory->size * sizeof(Item));
qsort(sorted, (size_t)inventory->size, sizeof(Item), item_compare);
size_t used = 0;
output[0] = '\0';
for (int i = 0; i < inventory->size; ++i)
used += (size_t)snprintf(output + used, 1024 - used, "%s%s:%d", i ? " " : "", sorted[i].name, sorted[i].quantity);
}
#endif
main.c
#include "inventory.h"
int main(void) {
Inventory inventory = {0};
char command[5], name[11], report[1024];
int count, accepted = 0;
while (scanf("%4s %10s %d", command, name, &count) == 3) {
bool ok = strcmp(command, "add") == 0
? inventory_add(&inventory, name, count)
: inventory_take(&inventory, name, count);
if (ok) ++accepted;
}
inventory_report(&inventory, report);
printf("%d%s%s\n", accepted, report[0] ? " " : "", report);
return 0;
}
Inventory.swiftとFunctions.swiftにSwiftのAPIを実装してください。提供された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プレイグラウンド