Menu
CoddyTech

Ruby 방 객체 포팅하기

Coddy의 Ruby 개발자를 위한 Lua 코스 레슨. 48개 중 48번째.

challenge icon

챌린지

중급

이 Ruby 프로그램 전체를 Lua 모듈로 옮기세요. 첫 번째 줄은 음수가 아닌 객실 수용 인원이고, 나머지 줄은 부호가 있는 정수 예약 요청입니다. 엄격히 양수이며 수용 인원에 맞는 요청만 승인하세요. 요청이 거부되면 사용된 좌석 수는 변경되지 않아야 합니다. remaining:accepted를 반환하세요. Model.new(capacity)는 수용 인원인 capacity와 사용된 좌석 수인 used를 노출하며, used의 초기값은 0입니다. Model:reserve(seats)는 불리언 값을 반환하며, 성공한 경우에만 상태를 변경합니다. 객실은 서로 독립적이어야 합니다. Ruby 인스턴스 변수의 불변 조건을 명시적인 Lua 테이블 상태로 옮기세요.

Ruby 객실 참고 코드

class Room
  attr_reader :capacity, :used
  def initialize(capacity)
    @capacity = capacity
    @used = 0
  end
  def reserve(seats)
    return false if seats <= 0 || @used + seats > @capacity
    @used += seats
    true
  end
end
lines = STDIN.read.lines.map(&:chomp)
room = Room.new(Integer(lines.shift, 10))
accepted = lines.count { |line| room.reserve(Integer(line, 10)) }
puts "#{room.capacity - room.used}:#{accepted}"

app.lua와 model.lua를 수정하세요. 화면에 보이는 잠긴 main.lua는 표준 입력을 줄 목록으로 읽고, 공개 API를 확인한 다음 app.run(lines)을 호출하고, 반환된 값 하나를 마지막 줄 바꿈과 함께 출력합니다. 진단 메시지는 출력하지 마세요. 객실 작업의 입력은 비어 있지 않으며, 재고 입력은 비어 있을 수 있습니다.

직접 해보기

-- 공개 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))

Ruby 개발자를 위한 Lua의 모든 레슨

직접 연습해 보세요: 온라인 Lua 컴파일러