Menu
CoddyTech

部屋の状態管理をCに移植する

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

challenge icon

チャレンジ

中級

C版では状態を構造体に保存し、そのアドレスを関数に渡します。Luaでは状態を新しいテーブルに保存し、コロン呼び出しでレシーバーを渡します。Cのクラスや継承機能は関係ありません。

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

Cの参照実装

#include <stdio.h>
#include <stdbool.h>

struct Room { long capacity; long used; };

static bool reserve(struct Room *room, long seats) {
    if (seats <= 0 || seats > room->capacity - room->used) return false;
    room->used += seats;
    return true;
}

int main(void) {
    struct Room room = {0, 0};
    if (scanf("%ld", &room.capacity) != 1 || room.capacity < 0) return 1;
    size_t accepted = 0;
    long seats;
    int scanned;
    while ((scanned = scanf("%ld", &seats)) == 1) {
        if (reserve(&room, seats)) ++accepted;
    }
    if (scanned != EOF || ferror(stdin)) return 1;
    printf("%ld:%zu\n", room.capacity - room.used, accepted);
    return ferror(stdout) ? 1 : 0;
}

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))

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

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