Rust 방 오브젝트 포팅하기
Coddy의 Rust 개발자를 위한 Lua 코스 레슨. 48개 중 48번째.
챌린지
중급Rust 참조 구현을 옮기세요. 첫 번째 입력 줄은 음이 아닌 방 수용 인원이고, 나머지 줄은 부호가 있는 정수 예약 요청입니다. 엄격히 양수이고 수용 가능한 요청만 승인하세요. 실패한 요청은 사용된 좌석 수를 변경하지 않습니다. remaining:accepted를 반환하세요. model.lua에서 Model.new(capacity)와 Model:reserve(seats)를 구현하세요. reserve는 불리언을 반환합니다. 실행마다 새 객체를 사용하세요.
app.lua, model.lua를 수정하세요. 화면에 보이는 잠금된 main.lua는 표준 입력을 줄의 시퀀스로 읽고, app.run(lines)을 호출한 다음 반환값을 마지막 줄바꿈 하나와 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 입력이 비어 있으면 빈 시퀀스가 됩니다. 모든 숫자 입력은 오버플로를 일으키지 않을 만큼 작습니다.
공개 API 확인: Model.new(capacity)는 capacity와 used를 노출하며, used는 처음에 0입니다. reserve는 불리언을 반환하며, 양수이면서 수용 가능한 요청에 대해서만 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의 논리 연산자를 불리언에서 정수로 변환하는 데 사용하지 마세요.
직접 해보기
-- 공개 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 컴파일러