방 오브젝트 포팅하기
Coddy의 GDScript 개발자를 위한 Luau 코스 레슨. 48개 중 48번째.
챌린지
중급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의 초기값은 0입니다. reserve는 불리언을 반환하며, 양수 요청이 수용 인원에 맞는 경우에만 used를 갱신합니다. 방 객체는 서로 독립적입니다. 잠긴 드라이버는 app.run을 호출하기 전에 이 동작을 확인합니다. 확인에 성공하면 아무것도 출력하지 않습니다.
참조 구현은 표준 입력을 읽기 위해 최소한의 SceneTree 하네스를 사용합니다. 형식이 올바르고 비어 있지 않은 줄로 이루어진 이 입력 범위에서는 빈 줄 확인으로 EOF에서 종료됩니다. 비즈니스 모델과 출력 규약을 포팅하세요. 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 컴파일러