Rust 인벤토리 포팅하기
Coddy의 Rust 개발자를 위한 Lua 코스 레슨. 48개 중 47번째.
챌린지
중급참조 Rust 프로그램을 Lua 모듈로 옮기세요. 각 입력 줄은 소문자 ASCII 이름, 콜론, 부호가 있는 정수 델타로 구성됩니다. 이름별로 합산하고, 최종 합계가 양수인 항목만 남긴 다음 이름을 오름차순으로 정렬하여 쉼표로 연결한 name=total 항목을 반환하세요. 남은 항목이 없으면 empty를 반환하세요. inventory.lua에서 inventory.aggregate(lines)를 구현하세요. 결과 형식 지정은 app에서 처리합니다. 모든 입력 줄은 올바른 형식입니다.
app.lua, inventory.lua를 수정하세요. 잠겨 있어 표시되는 main.lua는 표준 입력을 줄의 시퀀스로 읽고, app.run(lines)을 호출한 뒤 반환값을 마지막 줄바꿈과 함께 출력합니다. 진단 메시지를 출력하거나 모듈 이름을 변경하지 마세요. 빈 입력은 빈 시퀀스가 됩니다. 모든 숫자 입력은 오버플로가 발생하지 않을 만큼 작습니다.
공개 API 검사: inventory.aggregate(lines)는 부호가 있는 델타를 합산한 새 테이블을 반환하며, 합계가 0인 항목도 유지합니다. 빈 입력은 빈 테이블을 반환합니다. 형식 지정과 필터링은 app에서 처리합니다. 잠긴 드라이버는 app.run을 호출하기 전에 이 동작을 확인합니다. 성공하면 이 검사에서는 아무것도 출력하지 않습니다.
Rust 2021 참조 코드
use std::collections::BTreeMap;
use std::io::{self, Read};
fn aggregate(input: &str) -> BTreeMap<String, i64> {
let mut counts = BTreeMap::new();
for line in input.lines() {
let (name, delta) = line.split_once(':').unwrap();
*counts.entry(name.to_owned()).or_insert(0) += delta.parse::<i64>().unwrap();
}
counts
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
let rows: Vec<_> = aggregate(&input).into_iter()
.filter(|(_, total)| *total > 0)
.map(|(name, total)| format!("{}={}", name, total)).collect();
println!("{}", if rows.is_empty() { "empty".to_owned() } else { rows.join(",") });
}
Rust의 BTreeMap은 entry와 or_insert(0)을 사용해 누락된 개수를 초기화하고 키 순서대로 순회합니다. Lua에서는 키가 없는 경우와 저장된 값이 0인 경우를 구분하고, 부호가 있는 델타를 누적한 다음 보고서 키를 명시적으로 정렬하세요. 여기서 부호가 있는 정수는 선택적인 - 뒤에 숫자가 오는 형식이며, 더하기 기호는 입력되지 않습니다. 집계와 필터링을 분리하여 공개 모듈이 0 이하의 합계도 반환하도록 하세요.
직접 해보기
-- 공개 API 검사
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
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 컴파일러