Menu
CoddyTech

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

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

challenge icon

チャレンジ

中級

Rustの参照実装を移植してください。最初の入力行は0以上の部屋の定員で、残りの行は符号付き整数の予約リクエストです。厳密に正のリクエストで、定員内に収まるものだけを受け付けます。失敗したリクエストでは使用済み座席数を変更しません。remaining:acceptedを返してください。model.luaでModel.new(capacity)とModel:reserve(seats)を実装します。reserveはbooleanを返します。実行ごとに新しいオブジェクトを使用してください。

app.luaとmodel.luaを編集してください。表示されているロック済みのmain.luaは、標準入力を一連の行として読み込み、app.run(lines)を呼び出し、返された値を最後に改行を1つ付けて出力します。診断メッセージを出力したり、モジュール名を変更したりしないでください。入力が空の場合、一連の行は空です。数値入力はすべてオーバーフローを避けられる範囲です。

公開APIの確認: Model.new(capacity)はcapacityとusedを公開し、usedの初期値は0です。reserveはbooleanを返し、正のリクエストが定員内に収まる場合にのみusedを更新します。部屋はそれぞれ独立しています。ロック済みのドライバーはapp.runを呼び出す前にこの動作を確認します。成功した場合、これらの確認では何も出力されません。

Rust 2021の参照実装

use std::io::{self, Read};
struct Room { capacity: i64, used: i64 }
impl Room {
    fn new(capacity: i64) -> Self { Self { capacity, used: 0 } }
    fn reserve(&mut self, seats: i64) -> bool {
        if seats <= 0 || seats > self.capacity - self.used { return false; }
        self.used += seats;
        true
    }
    fn remaining(&self) -> i64 { self.capacity - self.used }
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let mut values = input.split_whitespace().map(|s| s.parse::<i64>().unwrap());
    let mut room = Room::new(values.next().unwrap());
    let mut accepted = 0;
    for seats in values { if room.reserve(seats) { accepted += 1; } }
    println!("{}:{}", room.remaining(), accepted);
}

Rustの構造体は、モジュールの外部からフィールドを非公開にし、共有借用によるオブザーバーを公開します。Luaの仕様では、ドライバーによる確認のためにcapacityとusedを公開しますが、予約の動作は同じです。各部屋を個別に割り当ててください。リクエストに失敗した場合は、状態を変更してはいけません。Luaの論理演算子をbooleanから整数への変換に使わないでください。

自分で試してみよう

-- 公開 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))

Rust開発者のためのLuaのすべてのレッスン

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