Menu
CoddyTech

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

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

challenge icon

チャレンジ

中級

PHP の参照実装を移植してください。最初の入力行は 0 以上の部屋の定員で、残りの行は符号付き整数の予約リクエストです。正の値で、かつ定員に収まるリクエストだけを受け付けてください。失敗したリクエストでは使用済み座席数を変更しません。remaining:accepted を返してください。model.lua に Model.new(capacity) と Model:reserve(seats) を実装してください。reserve は真偽値を返します。実行ごとに新しいオブジェクトを使ってください。

PHP の参照実装

<?php
class Room {
    public int $capacity;
    public int $used = 0;
    public function __construct(int $capacity) { $this->capacity = $capacity; }
    public function reserve(int $seats): bool {
        if ($seats <= 0 || $this->used + $seats > $this->capacity) {
            return false;
        }
        $this->used += $seats;
        return true;
    }
}
$room = new Room((int) fgets(STDIN));
$accepted = 0;
while (($line = fgets(STDIN)) !== false) {
    if ($room->reserve((int) $line)) { $accepted++; }
}
echo ($room->capacity - $room->used), ":", $accepted, "\n";

app.lua と model.lua を編集してください。表示されているロック済みの main.lua は標準入力を一連の行として読み込み、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))

PHP開発者のためのLuaのすべてのレッスン

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