포팅: 재고 명령어
Coddy의 Rust 개발자를 위한 Swift 코스 레슨. 48개 중 47번째.
챌린지
중급Rust 참조 구현을 Swift로 옮기세요. Inventory()를 구현하고, add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int, report() -> String를 제공하세요. Add는 양수 개수만 허용합니다. Take는 양수이면서 현재 재고 이하인 개수만 허용합니다. 거부된 요청은 상태를 전혀 변경하지 않으며, 알 수 없는 수량은 0입니다. 성공적으로 처리한 take는 재고가 0인 항목도 유지합니다. 저장된 모든 이름을 오름차순으로 정렬하고, 공백으로 구분해 name:quantity 형식으로 보고하세요. 입력에는 0개에서 40개까지의 명령 트리플이 들어 있습니다. 형식은 add name count 또는 take name count입니다. 이름은 최대 10글자의 소문자 ASCII 단어이고, 개수는 -10부터 100까지입니다. 성공한 명령의 개수를 출력하고, 보고 내용이 비어 있지 않을 때만 그 뒤에 공백과 보고 내용을 출력하세요.
필수 API와 solve(_ input: String) -> String을 구현하세요. 마지막 개행 없이 출력 문자열을 반환하고, 편집 가능한 코드에서 출력하지 마세요. 잠긴 드라이버는 추가 유효 입력으로 API를 별도로 검사한 다음, 반환된 문자열을 정확히 하나의 개행과 함께 출력합니다. 모든 숫자 연산은 Int 범위 안에서 이루어집니다.
동일한 입력 및 출력 규약을 위한 완전한 Rust 참조 구현:
use std::collections::BTreeMap;
use std::io::{self, Read};
#[derive(Default)]
struct Inventory { stock: BTreeMap<String, i64> }
impl Inventory {
fn quantity(&self, name: &str) -> i64 { self.stock.get(name).copied().unwrap_or(0) }
fn add(&mut self, name: &str, count: i64) -> bool {
if count <= 0 { return false; }
let next = self.quantity(name) + count;
self.stock.insert(name.to_owned(), next);
true
}
fn take(&mut self, name: &str, count: i64) -> bool {
let available = self.quantity(name);
if count <= 0 || count > available { return false; }
self.stock.insert(name.to_owned(), available - count);
true
}
fn report(&self) -> String {
self.stock.iter().map(|(name, count)| format!("{}:{}", name, count))
.collect::<Vec<_>>().join(" ")
}
}
fn solve(input: &str) -> String {
let tokens: Vec<&str> = input.split_whitespace().collect();
let mut stock = Inventory::default();
let mut accepted = 0;
for command in tokens.chunks_exact(3) {
let count: i64 = command[2].parse().unwrap();
let ok = if command[0] == "add" { stock.add(command[1], count) }
else { stock.take(command[1], count) };
if ok { accepted += 1; }
}
let report = stock.report();
if report.is_empty() { accepted.to_string() } else { format!("{} {}", accepted, report) }
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).unwrap();
println!("{}", solve(&input));
}코드는 Inventory.swift, Functions.swift에 작성하세요. main.swift에는 제공된 입력/출력 코드가 있으며 수정할 수 없습니다.
직접 해보기
import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 공개 API 검사 시작
let apiOK = apiChecks(input)
// 공개 API 검사 끝
if apiOK { print(solve(input)) } else { print("API mismatch") }
Rust 개발자를 위한 Swift의 모든 레슨
직접 연습해 보세요: Swift 플레이그라운드