Menu
CoddyTech

Finale: Registro di magazzino

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

challenge icon

Sfida

Medio

Porta il riferimento PHP completo nell’API Rust fornita. I valori di stato restituiti da PHP diventano valori Rust espliciti di tipo Result; i riferimenti agli oggetti conservati negli array diventano stato Rust posseduto. 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 inizia 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 inizia vuoto; il suo metodo 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 quantità zero. report(&self) -> String elenca solo le scorte positive come name:quantity, in ordine alfabetico per nome, separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal resoconto sulle righe successive. Le chiamate a report non modificano lo stato. L’array entries di PHP memorizza riferimenti agli oggetti Stock; Rust dovrebbe possedere i nomi e i valori delle scorte in una mappa. Mantieni la distinzione tra un elemento mancante e un elemento 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 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 fornito per input/output e non può essere modificato.

Riferimento PHP completo per lo stesso contratto di input valido:

<?php
declare(strict_types=1);
final class Stock {
    private int $amount = 0;
    public function quantity(): int { return $this->amount; }
    public function apply(int $delta): bool {
        $next = $this->amount + $delta;
        if ($next < 0) return false;
        $this->amount = $next;
        return true;
    }
}
final class Ledger {
    private array $entries = [];
    public function apply(string $name, int $delta): bool {
        $stock = $this->entries[$name] ?? new Stock();
        if (!$stock->apply($delta)) return false;
        $this->entries[$name] = $stock;
        return true;
    }
    public function quantity(string $name): ?int {
        return isset($this->entries[$name]) ? $this->entries[$name]->quantity() : null;
    }
    public function report(): string {
        $names = array_keys($this->entries);
        sort($names, SORT_STRING);
        $rows = [];
        foreach ($names as $name) {
            $amount = $this->entries[$name]->quantity();
            if ($amount > 0) $rows[] = $name . ":" . $amount;
        }
        return $rows === [] ? "empty" : implode("\n", $rows);
    }
}
$text = trim(stream_get_contents(STDIN));
$words = $text === "" ? [] : preg_split('/\s+/', $text);
$ledger = new Ledger();
$rejected = 0;
for ($index = 0; $index < count($words); $index += 2) {
    if (!$ledger->apply($words[$index], (int) $words[$index + 1])) $rejected++;
}
echo "rejected:", $rejected, "\n", $ledger->report(), "\n";

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 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 VERIFICHE DELL'API PUBBLICA
    println!("{}", exercise::solve(&input));
}

Tutte le lezioni di Rust per sviluppatori PHP

Esercitati da solo: Compilatore Rust online