Menu
CoddyTech

Luaのルームオブジェクトを移植する

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

challenge icon

チャレンジ

中級

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

Lua 5.1 リファレンス

-- Lua 5.1 reference with explicit module registration.
package.preload["app"]=function()
local M = {}
function M.run(lines)
  local Model=require("model")
  local room=Model.new(tonumber(lines[1]))
  local accepted=0
  for i=2,#lines do if room:reserve(tonumber(lines[i])) then accepted=accepted+1 end end
  return (room.capacity-room.used) .. ":" .. accepted
end
return M
end
package.preload["model"]=function()
local Model={}
Model.__index=Model
function Model.new(capacity) return setmetatable({capacity=capacity,used=0},Model) end
function Model:reserve(seats)
  if seats<=0 or self.used+seats>self.capacity then return false end
  self.used=self.used+seats;return true
end
return Model
end
-- Public API checks
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))

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

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

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