Menu
CoddyTech

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

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

challenge icon

チャレンジ

中級

このRubyプログラム全体をLuaモジュールに移植してください。最初の行は0以上の部屋の収容人数で、残りの行は符号付き整数の予約リクエストです。厳密に正のリクエストのうち、収容可能なものだけを受け付けます。リクエストに失敗した場合、使用済み座席数は変更してはいけません。remaining:acceptedを返します。Model.new(capacity)は、capacityと、初期値が0のusedを公開します。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)を呼び出して、返された値を1つだけ末尾の改行とともに出力します。診断メッセージは出力しないでください。部屋の課題では入力は空ではありませんが、在庫の入力は空の場合があります。

自分で試してみよう

-- 公開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オンラインコンパイラ