Menu
CoddyTech

Porting: Comandi dell'inventario

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

challenge icon

Sfida

Medio

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

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

extends SceneTree
class Inventory:
    var _stock: Dictionary = {}
    func quantity(name: String) -> int:
        return _stock.get(name, 0)
    func add(name: String, count: int) -> bool:
        if count <= 0:
            return false
        _stock[name] = quantity(name) + count
        return true
    func take(name: String, count: int) -> bool:
        var available = quantity(name)
        if count <= 0 or count > available:
            return false
        _stock[name] = available - count
        return true
    func report() -> String:
        var names = _stock.keys()
        names.sort()
        var rows: Array[String] = []
        for name in names:
            rows.append("%s:%d" % [name, _stock[name]])
        return " ".join(rows)
func read_tokens() -> Array[String]:
    var bytes = PackedByteArray()
    while true:
        var chunk = OS.read_buffer_from_stdin(4096)
        if chunk.is_empty():
            break
        bytes.append_array(chunk)
    var pattern = RegEx.new()
    pattern.compile("\\S+")
    var tokens: Array[String] = []
    for found in pattern.search_all(bytes.get_string_from_utf8()):
        tokens.append(found.get_string())
    return tokens
func _init():
    var tokens = read_tokens()
    var inventory = Inventory.new()
    var accepted = 0
    for index in range(0, tokens.size(), 3):
        var count = tokens[index + 2].to_int()
        var success: bool
        if tokens[index] == "add":
            success = inventory.add(tokens[index + 1], count)
        else:
            success = inventory.take(tokens[index + 1], count)
        if success:
            accepted += 1
    var report = inventory.report()
    print(str(accepted) + (" " + report if not report.is_empty() else ""))
    quit()

Il tuo codice va inserito in Inventory.swift, Functions.swift. main.swift contiene il codice fornito per input e 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 DEI CONTROLLI DELL'API PUBBLICA
let apiOK = apiChecks(input)
// FINE DEI CONTROLLI DELL'API PUBBLICA
if apiOK { print(solve(input)) } else { print("API mismatch") }

Tutte le lezioni di Swift per sviluppatori GDScript

Esercitati da solo: Playground Swift