Menu
CoddyTech

部屋のオブジェクトを移植する

Coddyの「Swift開発者のためのLuau」コースのレッスン 48/48。

challenge icon

チャレンジ

中級

Swiftのリファレンス実装を移植してください。最初の入力行は0以上の部屋の収容人数で、残りの行は符号付き整数の予約リクエストです。0より大きく、収容人数に収まるリクエストだけを受け付けます。失敗したリクエストでは使用済み座席数は変わりません。remaining:acceptedを返します。model.luauにModel.new(capacity)とModel:reserve(seats)を実装してください。reserveは真偽値を返します。実行ごとに新しいオブジェクトを使用してください。

Swiftのリファレンス実装

final class Room {
    let capacity: Int
    private(set) var used = 0
    init(capacity: Int) { self.capacity = capacity }
    func reserve(_ seats: Int) -> Bool {
        guard seats > 0 && seats <= capacity - used else { return false }
        used += seats
        return true
    }
}
let room = Room(capacity: Int(readLine()!)!)
var accepted = 0
while let line = readLine() {
    if room.reserve(Int(line)!) { accepted += 1 }
}
print("\(room.capacity - room.used):\(accepted)")

app.luauとmodel.luauを編集してください。表示されているロック済みのmain.luauは、標準入力を一連の行として読み込み、app.run(lines)を呼び出し、その戻り値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合、一連の行は空になります。すべての数値入力はオーバーフローしない範囲です。

公開APIのチェック: Model.new(capacity)はcapacityとusedを公開し、usedは初期値で0です。reserveは真偽値を返し、正のリクエストが収まる場合にのみusedを更新します。部屋同士は独立しています。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。成功した場合、これらのチェックは何も出力しません。

自分で試してみよう

-- 公開APIのチェック
do
local Model=require("./model")
local a,b=Model.new(5),Model.new(2)
assert(a:reserve(6)==false and a.used==0,"oversized reservation must not mutate")
assert(a:reserve(0)==false and a:reserve(-1)==false and a.used==0,"nonpositive requests are rejected")
assert(a:reserve(2)==true and a.used==2,"accepted seats update used")
assert(a:reserve(3)==true and a.used==5 and a.capacity==5,"exact fit succeeds without changing capacity")
assert(b.used==0 and b.capacity==2,"rooms must be independent")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

Swift開発者のためのLuauのすべてのレッスン

自分で練習してみよう: Luauオンラインコンパイラ