Menu
CoddyTech

部屋オブジェクトを移植する

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

challenge icon

チャレンジ

中級

Go のリファレンスを移植してください。最初の入力行は 0 以上の部屋の定員で、残りの行は符号付き整数の予約リクエストです。厳密に正のリクエストのうち、定員に収まるものだけを受け入れます。失敗したリクエストでは使用済み座席数は変わりません。remaining:accepted を返します。model.luau に 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.luau と model.luau を編集してください。表示されているロック済みの main.luau は stdin を一連の行に読み込み、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))

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

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