Menu
CoddyTech

移植房间对象

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

challenge icon

挑战

中等

移植 GDScript 参考实现。第一行输入是非负的房间容量,其余各行是带符号的整数预订请求。只接受严格大于零且不超出容量的请求。失败的请求不会改变已使用的座位数。返回 remaining:accepted。在 model.luau 中实现 Model.new(capacity) 和 Model:reserve(seats);reserve 返回布尔值。每次运行都使用一个新对象。

GDScript 参考实现

extends SceneTree
class Room extends RefCounted:
    var capacity: int
    var used: int = 0
    func _init(limit: int):
        capacity = limit
    func reserve(seats: int) -> bool:
        if seats <= 0 or used + seats > capacity:
            return false
        used += seats
        return true
func _init():
    var room = Room.new(int(OS.read_string_from_stdin()))
    var accepted = 0
    while true:
        var line = OS.read_string_from_stdin().strip_edges()
        if line == "":
            break
        if room.reserve(int(line)):
            accepted += 1
    print(str(room.capacity - room.used) + ":" + str(accepted))
    quit()

编辑 app.luau、model.luau。可见的锁定文件 main.luau 会将标准输入读入一个行序列,调用 app.run(lines),并用一个末尾换行符打印其返回值。不要打印诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。

公共 API 检查:Model.new(capacity) 会公开 capacity 和 used,其中 used 初始为零。reserve 返回布尔值,并且只会在请求为正数且不超出容量时更新 used。各个房间互相独立。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。

参考实现使用一个精简的 SceneTree 框架来读取标准输入。对于格式正确且不含空行的输入,此处的空行检查会在到达文件末尾时终止。移植业务模型和输出约定;Luau 驱动程序会提供输入行,不需要引擎生命周期。

亲手试试

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

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

自己练习: Luau 在线编译器