Menu
CoddyTech

Porting: comandi di inventario

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

challenge icon

Sfida

Medio

Adatta il riferimento in Rust a Swift. Implementa Inventory() con add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int e report() -> String. Add accetta solo conteggi positivi. Take accetta solo conteggi positivi non superiori alle scorte attuali. I rifiuti preservano tutto lo stato; le quantità sconosciute sono zero. Le operazioni Take riuscite mantengono le voci con scorte pari a zero. Il report elenca tutti i nomi memorizzati in ordine crescente, come name:quantity, separati da spazi. L’input contiene da 0 a 40 triplette di comandi: add name count oppure take name count. I nomi sono parole composte da lettere ASCII minuscole, lunghe al massimo 10 lettere; i conteggi vanno da -10 a 100. L’output contiene il numero di comandi riusciti, seguito da uno spazio e dal report solo se non è vuoto.

Implementa le API richieste e solve(_ input: String) -> String. Restituisci il testo dell’output senza una nuova riga finale; non stampare nel codice modificabile. Il driver bloccato verifica indipendentemente le API con altri input validi, quindi stampa il testo restituito seguito da esattamente una nuova riga. Tutte le operazioni numeriche rimangono entro i limiti di Int.

Riferimento completo in Rust per lo stesso contratto di input e output:

use std::collections::BTreeMap;
use std::io::{self, Read};
#[derive(Default)]
struct Inventory { stock: BTreeMap<String, i64> }
impl Inventory {
    fn quantity(&self, name: &str) -> i64 { self.stock.get(name).copied().unwrap_or(0) }
    fn add(&mut self, name: &str, count: i64) -> bool {
        if count <= 0 { return false; }
        let next = self.quantity(name) + count;
        self.stock.insert(name.to_owned(), next);
        true
    }
    fn take(&mut self, name: &str, count: i64) -> bool {
        let available = self.quantity(name);
        if count <= 0 || count > available { return false; }
        self.stock.insert(name.to_owned(), available - count);
        true
    }
    fn report(&self) -> String {
        self.stock.iter().map(|(name, count)| format!("{}:{}", name, count))
            .collect::<Vec<_>>().join(" ")
    }
}
fn solve(input: &str) -> String {
    let tokens: Vec<&str> = input.split_whitespace().collect();
    let mut stock = Inventory::default();
    let mut accepted = 0;
    for command in tokens.chunks_exact(3) {
        let count: i64 = command[2].parse().unwrap();
        let ok = if command[0] == "add" { stock.add(command[1], count) }
                 else { stock.take(command[1], count) };
        if ok { accepted += 1; }
    }
    let report = stock.report();
    if report.is_empty() { accepted.to_string() } else { format!("{} {}", accepted, report) }
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    println!("{}", solve(&input));
}

Il tuo codice va inserito in Inventory.swift, Functions.swift. main.swift contiene il codice fornito per input/output e non può essere modificato.

Provalo tu

import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// INIZIO VERIFICHE DELL'API PUBBLICA
let apiOK = apiChecks(input)
// FINE VERIFICHE DELL'API PUBBLICA
if apiOK { print(solve(input)) } else { print("API mismatch") }

Tutte le lezioni di Swift per sviluppatori Rust

Esercitati da solo: Playground Swift