Finale: Registro di magazzino
Lezione 47 di 48 del corso Rust per sviluppatori Luau di Coddy.
Sfida
MedioTrasporta l’intero riferimento Luau 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 gli elementi mancanti da quelli con valore zero. report(&self) -> String elenca solo le scorte positive come name:quantity, in ordine di nome e separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal resoconto sulle righe successive. Le chiamate a report non modificano lo stato. La tabella entries del riferimento Luau memorizza riferimenti a tabelle Stock mutabili; Rust deve possedere i nomi e le scorte. Il riferimento ordina esplicitamente le chiavi ASCII perché la normale iterazione della tabella non garantisce un ordine.
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 separatamente, 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 Luau distingue una scorta mancante con nil da una presente con valore zero. Il risultato booleano segnala un errore senza generare eccezioni, e un nuovo elemento rifiutato non viene mai inserito. I limiti interi indicati sono rappresentabili esattamente in Luau number; Rust usa i tipi interi specificati. Trasporta il comportamento nei moduli Rust richiesti.
Programma di riferimento Luau completo e autonomo:
-- Luau console reference; io is supplied by the course runner.
local Stock = {}
Stock.__index = Stock
function Stock.new() return setmetatable({amount = 0}, Stock) end
function Stock:quantity() return self.amount end
function Stock:apply(delta)
local next_amount = self.amount + delta
if next_amount < 0 then return false end
self.amount = next_amount
return true
end
local Ledger = {}
Ledger.__index = Ledger
function Ledger.new() return setmetatable({entries = {}}, Ledger) end
function Ledger:apply(name, delta)
local stock = self.entries[name] or Stock.new()
if not stock:apply(delta) then return false end
self.entries[name] = stock
return true
end
function Ledger:quantity(name)
local stock = self.entries[name]
if stock == nil then return nil end
return stock:quantity()
end
function Ledger:report()
local names, rows = {}, {}
for name in pairs(self.entries) do names[#names + 1] = name end
table.sort(names)
for _, name in ipairs(names) do
local amount = self.entries[name]:quantity()
if amount > 0 then rows[#rows + 1] = name .. ":" .. amount end
end
return #rows == 0 and "empty" or table.concat(rows, "\n")
end
local ledger, rejected = Ledger.new(), 0
local words = {}
for word in io.read("*a"):gmatch("%S+") do words[#words + 1] = word end
for index = 1, #words, 2 do
if not ledger:apply(words[index], tonumber(words[index + 1])) then
rejected = rejected + 1
end
end
print("rejected:" .. rejected .. "\n" .. ledger:report())
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 DELLE VERIFICHE 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 DELLE VERIFICHE DELL'API PUBBLICA
println!("{}", exercise::solve(&input));
}
Tutte le lezioni di Rust per sviluppatori Luau
1Primi programmi in Rust
Eseguire moduli RustOutput e commentiModuli e visibilitàAssociazioni e tipiNumeri e conversioniRiepilogo: fattura di magazzino4Proprietà e prestito
Proprietà e trasferimentiPrestiti condivisiPrestiti mutabiliDurate e visteRiepilogo dei prestiti3Funzioni e sequenze
Funzioni e valori restituitiArray e sezioniVettori e iterazioneRiepilogo: registrare le letture6Assenza ed errore
Option e pattern matchingResult e propagazioneParsing e validazioneContratti degli erroriRiepilogo degli errori9Progetto: Deposito pacchi
Accettazione al depositoReport sul peso del depositoEsercitati da solo: Compilatore Rust online