Abschluss: Bestandsbuch
Lektion 47 von 48 im Kurs Rust für Swift-Entwickler von Coddy.
Aufgabe
MittelPortiere il riferimento Swift completo nell'API Rust fornita. L'input contiene al massimo 100 righe name delta; i nomi sono parole ASCII minuscole di al massimo 31 byte e i delta vanno da -1000 a 1000. L'input vuoto è valido. Stock::new() -> Stock parte da zero; quantity(&self) -> i32 lo legge; apply(&mut self, delta: i32) -> Result<(), &'static str> rifiuta una quantità risultante negativa con Err("negative"), lasciando invariato lo stato. Ledger::new() -> Ledger parte vuoto; il suo apply(&mut self, name: &str, delta: i32) ha lo stesso contratto di risultato e non deve creare un elemento mancante in caso di rifiuto. quantity(&self, name: &str) -> Option<i32> distingue un elemento mancante da uno con valore zero. report(&self) -> String elenca solo le scorte positive nel formato name:quantity, ordinate per nome e separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal report nelle righe successive. Le chiamate a report non modificano lo stato. Il Dictionary di Swift memorizza valori Stock; Rust dovrebbe possedere i nomi e le scorte. Il riferimento ordina esplicitamente le chiavi ASCII, perché l'attraversamento del dizionario non garantisce un ordine ordinato.
Implementa le API esportate richieste e restituisci il risultato da exercise::solve(input: &str) -> String senza una nuova riga finale. Non stampare nel codice modificabile. Il driver bloccato verifica le API richieste in modo indipendente, legge tutto lo stdin e stampa il testo restituito con una nuova riga finale.
Il tuo codice va inserito in exercise.rs, stock.rs, ledger.rs. main.rs contiene il codice di input/output fornito e non può essere modificato.
Il riferimento Swift distingue una scorta mancante da una presente con valore zero usando nil. Il risultato booleano segnala un errore senza generare un'eccezione e un nuovo elemento rifiutato non viene mai inserito. I limiti interi indicati rientrano nelle quantità Int32; Rust usa i tipi interi specificati. Porta il comportamento nei moduli Rust richiesti.
Programma di riferimento Swift completo e autonomo:
struct Stock {
private(set) var quantity: Int32 = 0
mutating func apply(_ delta: Int32) -> Bool {
let next = quantity + delta
guard next >= 0 else { return false }
quantity = next
return true
}
}
struct Ledger {
private var stocks: [String: Stock] = [:]
mutating func apply(_ name: String, _ delta: Int32) -> Bool {
var stock = stocks[name] ?? Stock()
guard stock.apply(delta) else { return false }
stocks[name] = stock
return true
}
func quantity(_ name: String) -> Int32? { stocks[name]?.quantity }
func report() -> String {
let rows = stocks.keys.sorted().compactMap { name -> String? in
let quantity = stocks[name]!.quantity
return quantity > 0 ? "\(name):\(quantity)" : nil
}
return rows.isEmpty ? "empty" : rows.joined(separator: "\n")
}
}
var words: [String] = []
while let line = readLine() { words += line.split(whereSeparator: { $0.isWhitespace }).map(String.init) }
var ledger = Ledger()
var rejected = 0
for index in stride(from: 0, to: words.count, by: 2) {
if !ledger.apply(words[index], Int32(words[index + 1])!) { rejected += 1 }
}
print("rejected:\(rejected)")
print(ledger.report())
Probier es selbst
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGINN DER ÖFFENTLICHEN API-TESTS
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
assert_eq!(ledger::Ledger::new().report(), "empty");
// ENDE DER ÖFFENTLICHEN API-TESTS
println!("{}", exercise::solve(&input));
}
Alle Lektionen in Rust für Swift-Entwickler
1Erste Rust-Programme
Rust-Module ausführenAusgabe und KommentareModule und SichtbarkeitBindungen und TypenZahlen und CastsRückblick: Speicherrechnung4Besitz und Ausleihen
Besitz und VerschiebungenGemeinsame AusleihenVeränderbare AusleihenLebenszeiten und SichtenRückblick auf das Ausleihen2Entscheidungen und Schleifen
Boolesche BedingungenIf-AusdrückeMatch und EnumsSchleifen und BereicheRückblick: Ladetor3Funktionen und Sequenzen
Funktionen und RückgabewerteArrays und SlicesVektoren und IterationRückblick: Messwerte erfassen6Abwesenheit und Fehlschläge
Option und Pattern MatchingResult und WeitergabeParsing und ValidierungFehlerverträgeRückblick auf FehlschlägeÜbe selbstständig: Online-Rust-Compiler