Menu
CoddyTech

移植 Go 房间状态程序

Coddy 面向 Go 开发者的 Lua 课程的第 48 课,共 48 课。

challenge icon

挑战

中等

Go 版本将房间状态存储在结构体中,并通过指针接收者方法更新状态。Lua 将状态存储在一个新建的表中,并通过冒号调用为方法提供接收者。请保持各个房间彼此独立,并在更改已使用数量之前拒绝无效预订。

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

Go 参考实现

package main
import("fmt";"io";"os";"strconv";"strings")
type Room struct {Capacity,Used int64}
func(r *Room) Reserve(seats int64)bool {
 if seats<=0 || seats>r.Capacity-r.Used {return false}
 r.Used+=seats
 return true
}
func main(){
 raw,err:=io.ReadAll(os.Stdin); if err!=nil {panic(err)}
 lines:=strings.Fields(string(raw))
 capacity,err:=strconv.ParseInt(lines[0],10,64); if err!=nil {panic(err)}
 room:=Room{Capacity:capacity}; accepted:=0
 for _,line:=range lines[1:] {seats,err:=strconv.ParseInt(line,10,64); if err!=nil {panic(err)}; if room.Reserve(seats){accepted++}}
 fmt.Printf("%d:%d\n",room.Capacity-room.Used,accepted)
}

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

公开 API 检查:Model.new(capacity) 会提供 capacity 和 used 属性,初始值为零。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))

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

自己练习: Lua 在线编译器