Menu
CoddyTech

Finale: Registro delle scorte

Lezione 47 di 48 del corso Rust per sviluppatori Lua di Coddy.

challenge icon

Sfida

Medio

Porta l’intero riferimento Lua nell’API Rust fornita. I valori di stato restituiti da Lua diventano valori Rust espliciti di tipo Result; gli oggetti contenuti nelle tabelle diventano stato Rust posseduto. 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 quantità zero. report(&self) -> String elenca solo le scorte positive come name:quantity, in ordine per nome e separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal resoconto nelle righe successive. Le chiamate a report non modificano lo stato. La tabella Lua memorizza riferimenti alle tabelle Stock; Rust dovrebbe 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 verifica le API richieste indipendentemente, 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 Lua completo per lo stesso contratto di input valido:

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 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 Lua

Esercitati da solo: Compilatore Rust online