Menu
CoddyTech

移植房间对象

Coddy 面向 JavaScript 开发者的 Luau 课程 课程的第 48 课,共 48 课。

challenge icon

挑战

中等

重构 JavaScript 参考代码。输入的第一行是非负的房间容量;其余行是有符号整数的预订请求。仅接受可以容纳且严格为正数的请求。失败的请求不会改变已使用的座位数。返回 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),并打印其返回值以及一个结尾换行符。请勿打印诊断信息或更改模块名称。空输入会生成空序列。所有数值输入都足够小,不会发生溢出。

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

面向 JavaScript 开发者的 Luau 课程中的所有课

自己练习: Luau 在线编译器