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),并输出其返回值(带一个末尾换行符)。请勿打印调试诊断信息或更改模块名称。空输入会生成一个空序列。所有数值输入都足够小,不会发生溢出。

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

面向 Lua 开发者的 Luau中的所有课

自己练习: Luau 在线编译器