Menu
CoddyTech

Porting: comandi di inventario

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

challenge icon

Sfida

Medio

Porta il riferimento PHP in 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 completate con successo mantengono le voci con scorte pari a zero. Il report elenca tutti i nomi memorizzati in ordine crescente nel formato name:quantity, separati da spazi. L'input contiene da 0 a 40 triple di comandi: add name count oppure take name count. I nomi sono parole in ASCII minuscolo fino a 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 di output senza newline finale; non stampare nel codice modificabile. Il driver bloccato verifica indipendentemente le API con input validi aggiuntivi, poi stampa il testo restituito con esattamente un newline. Tutte le operazioni numeriche rimangono entro i limiti di Int.

Riferimento PHP completo per lo stesso contratto di input e output:

<?php
declare(strict_types=1);
final class Inventory {
    private array $stock = [];
    public function quantity(string $name): int { return $this->stock[$name] ?? 0; }
    public function add(string $name, int $count): bool {
        if ($count <= 0) return false;
        $this->stock[$name] = $this->quantity($name) + $count;
        return true;
    }
    public function take(string $name, int $count): bool {
        $available = $this->quantity($name);
        if ($count <= 0 || $count > $available) return false;
        $this->stock[$name] = $available - $count;
        return true;
    }
    public function report(): string {
        $sorted = $this->stock;
        ksort($sorted, SORT_STRING);
        $parts = [];
        foreach ($sorted as $name => $quantity) $parts[] = "$name:$quantity";
        return implode(" ", $parts);
    }
}
function solve(string $input): string {
    $tokens = preg_split('/\s+/', trim($input), -1, PREG_SPLIT_NO_EMPTY);
    $stock = new Inventory();
    $accepted = 0;
    for ($i = 0; $i < count($tokens); $i += 3) {
        $name = $tokens[$i + 1];
        $count = (int)$tokens[$i + 2];
        $ok = $tokens[$i] === "add" ? $stock->add($name, $count) : $stock->take($name, $count);
        if ($ok) $accepted++;
    }
    $report = $stock->report();
    return (string)$accepted . ($report === "" ? "" : " " . $report);
}
echo solve(stream_get_contents(STDIN)), "\n";

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 PHP

Esercitati da solo: Playground Swift