Menu
CoddyTech

ルームオブジェクトの移植

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

challenge icon

チャレンジ

中級

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

JavaScriptのリファレンス

const fs=require("node:fs");
const raw=fs.readFileSync(0,"utf8");
const lines=raw.length ? raw.replace(/\n$/, "").split("\n") : [];
class Room {
  constructor(capacity) { this.capacity=capacity; this.used=0; }
  reserve(seats) {
    if (seats<=0 || this.used+seats>this.capacity) return false;
    this.used+=seats;
    return true;
  }
}
const room=new Room(Number(lines[0]));
let accepted=0;
for (const line of lines.slice(1)) if (room.reserve(Number(line))) accepted++;
console.log((room.capacity-room.used)+":"+accepted);

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

公開APIチェック: Model.new(capacity) は capacity と 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))

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

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