Finale: Registro di magazzino
Lezione 47 di 48 del corso Rust per sviluppatori GDScript di Coddy.
Sfida
MedioPorta l'intero riferimento GDScript nell'API Rust fornita. I valori di stato restituiti da GDScript diventano valori Rust Result espliciti; gli oggetti contenuti nei dizionari diventano stato Rust di proprietà. L'input contiene fino a 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 quando l'operazione viene rifiutata. 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, in ordine alfabetico dei nomi, separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal resoconto nelle righe successive. Le chiamate a report non modificano lo stato. Il Dictionary di GDScript memorizza riferimenti agli oggetti Stock; Rust deve possedere i nomi e i valori delle scorte in una mappa. Mantieni la distinzione tra un elemento mancante e uno con quantità zero.
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 controlla separatamente le API richieste, 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.
Riferimento GDScript completo per lo stesso contratto di input valido:
extends SceneTree
class Stock:
var amount = 0
func quantity() -> int:
return amount
func apply(delta: int) -> bool:
var next = amount + delta
if next < 0:
return false
amount = next
return true
class Ledger:
var entries = {}
func apply(label: String, delta: int) -> bool:
var stock = entries.get(label)
if stock == null:
stock = Stock.new()
if not stock.apply(delta):
return false
entries[label] = stock
return true
func quantity(label: String):
return entries[label].quantity() if entries.has(label) else null
func report() -> String:
var names = entries.keys()
names.sort()
var rows = PackedStringArray()
for label in names:
var amount = entries[label].quantity()
if amount > 0:
rows.append(label + ":" + str(amount))
return "empty" if rows.is_empty() else "\n".join(rows)
func _init():
var ledger = Ledger.new()
var rejected = 0
var whitespace = RegEx.new()
whitespace.compile("\\s+")
while true:
var line = OS.read_string_from_stdin()
if line.is_empty():
break
var words = whitespace.sub(line.strip_edges(), " ", true).split(" ", false)
if words.is_empty():
continue
if not ledger.apply(words[0], words[1].to_int()):
rejected += 1
print("rejected:%d\n%s" % [rejected, ledger.report()])
quit()
Provalo tu
#![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();
// INIZIO DEI TEST DELL'API PUBBLICA
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");
// FINE DEI TEST DELL'API PUBBLICA
println!("{}", exercise::solve(&input));
}
Tutte le lezioni di Rust per sviluppatori GDScript
1Primi programmi in Rust
Eseguire moduli RustOutput e commentiModuli e visibilitàBinding e tipiNumeri e conversioniRiepilogo: fattura di archiviazione4Possesso e prestito
Possesso e spostamentiPrestiti condivisiPrestiti mutabiliDurate e visteRiepilogo dei prestitiEsercitati da solo: Compilatore Rust online