Menu
CoddyTech

Finale: Registro scorte

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

challenge icon

Sfida

Medio

Porta il riferimento Kotlin completo nell’API Rust fornita. L’input contiene al massimo 100 righe name delta, con nomi composti da parole ASCII minuscole di al massimo 31 byte e delta compresi tra -1000 e 1000. L’input vuoto è valido. Stock::new() -> Stock parte da zero; quantity(&self) -> i32 ne legge il valore; apply(&mut self, delta: i32) -> Result<(), &'static str> rifiuta un risultato negativo per la quantità con Err("negative"), lasciando invariato lo stato. Ledger::new() -> Ledger parte vuoto; il suo apply(&mut self, name: &str, delta: i32) segue 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 come name:quantity, in ordine per nome e separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal report sulle righe successive. Le chiamate a report non modificano lo stato. Il riferimento Kotlin usa una mappa ordinata contenente riferimenti a istanze di Stock. In Rust, memorizza i nomi e i valori Stock in una mappa e converti il fallimento booleano nel contratto Result richiesto.

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 di input/output fornito e non può essere modificato.

Il tipo nullable Kotlin Int? distingue un elemento mancante da una quantità pari a zero; Rust usa Option<i32>. Il riferimento Kotlin segnala il rifiuto con un booleano, mentre le API Rust richieste restituiscono Result<(), &'static str>. Mantieni lo stato invariato in caso di fallimento e restituisci il valore letterale empty quando il report non contiene scorte positive.

Riferimento Kotlin completo per lo stesso contratto di input valido:

class Stock {
    private var amount = 0
    fun quantity(): Int = amount
    fun apply(delta: Int): Boolean {
        val next = amount + delta
        if (next < 0) return false
        amount = next
        return true
    }
}
class Ledger {
    private val entries = sortedMapOf<String, Stock>()
    fun apply(name: String, delta: Int): Boolean {
        val current = entries[name]
        if (current != null) return current.apply(delta)
        val candidate = Stock()
        if (!candidate.apply(delta)) return false
        entries[name] = candidate
        return true
    }
    fun quantity(name: String): Int? = entries[name]?.quantity()
    fun report(): String {
        val rows = entries.filterValues { it.quantity() > 0 }
            .map { (name, stock) -> name + ":" + stock.quantity() }
        return if (rows.isEmpty()) "empty" else rows.joinToString("\n")
    }
}
fun main() {
    val text = generateSequence(::readLine).joinToString("\n").trim()
    val words = if (text.isEmpty()) emptyList() else text.split(Regex("\\s+"))
    val ledger = Ledger()
    var rejected = 0
    for (index in words.indices step 2) {
        if (!ledger.apply(words[index], words[index + 1].toInt())) rejected++
    }
    println("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 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 Kotlin

Esercitati da solo: Compilatore Rust online