הסבה: פקודות מלאי
שיעור 47 מתוך 48 בקורס Swift למפתחי Rust של Coddy.
אתגר
בינוניהעבר את מימוש הייחוס ב-Rust ל-Swift. ממש את Inventory() עם add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int ו-report() -> String. הפעולה Add מקבלת רק כמויות חיוביות. הפעולה Take מקבלת רק כמויות חיוביות שאינן עולות על המלאי הנוכחי. דחיות אינן משנות את המצב; הכמויות של פריטים לא מוכרים הן אפס. פעולות Take מוצלחות משאירות רשומות שהמלאי שלהן אפס. הדיווח יכלול את כל השמות המאוחסנים בסדר עולה, בפורמט name:quantity ומופרדים ברווחים. הקלט מכיל 0 עד 40 שלשות פקודה: add name count או take name count. השמות הם מילים באותיות ASCII קטנות, באורך של עד 10 אותיות, והכמויות הן בין -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)!
// תחילת בדיקות PUBLIC API
let apiOK = apiChecks(input)
// סיום בדיקות PUBLIC API
if apiOK { print(solve(input)) } else { print("API mismatch") }
כל השיעורים ביחידה Swift למפתחי Rust
1תחילת העבודה עם Swift
עבודה עם קבציםקישוריות ושינוי ערכיםמספרים והמרותתנאים בוליאנייםסיכום: תעריף נסיעה4פונקציות ומערכים
פונקציות ותוויותInout וגישה בלעדיתטאפלים ותוצאות מרובותלמערכים יש סמנטיקה של ערךסיכום: מדרגות עולותתרגלו בעצמכם: Swift אונליין