Menu
CoddyTech

Porting: Comandi di inventario

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

challenge icon

Sfida

Medio

Porta il programma di riferimento Go 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 alla scorta attuale. I rifiuti preservano tutto lo stato; le quantità sconosciute sono zero. Le operazioni Take riuscite mantengono le voci con scorta 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 ASCII minuscole lunghe fino a 10 lettere; i conteggi vanno da -10 a 100. L'output è 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 newline finale; non stampare nel codice modificabile. Il driver bloccato verifica in modo indipendente le API su input validi aggiuntivi, quindi stampa il testo restituito con esattamente un newline. Tutte le operazioni numeriche restano entro i limiti di Int.

L'Inventory Go viene usato tramite un puntatore e possiede una mappa le cui chiavi vengono ordinate esplicitamente per il report. Copiare un valore mappa Go condividerebbe comunque le voci sottostanti. Mantieni l'API richiesta basata su un tipo di riferimento in Swift e tutto lo stato dopo i comandi rifiutati.

Programma di riferimento Go completo. Compila insieme questi file package main; main.go contiene l'unica funzione main. L'implementazione è volutamente completa per questo porting finale.

inventory.go

package main
import ("sort"; "strconv"; "strings")
type Inventory struct { stock map[string]int }
func NewInventory() *Inventory { return &Inventory{stock: make(map[string]int)} }
func (inventory *Inventory) Quantity(name string) int { return inventory.stock[name] }
func (inventory *Inventory) Add(name string, count int) bool {
    if count <= 0 { return false }
    inventory.stock[name] = inventory.Quantity(name) + count
    return true
}
func (inventory *Inventory) Take(name string, count int) bool {
    available := inventory.Quantity(name)
    if count <= 0 || count > available { return false }
    inventory.stock[name] = available - count
    return true
}
func (inventory *Inventory) Report() string {
    names := make([]string, 0, len(inventory.stock))
    for name := range inventory.stock { names = append(names, name) }
    sort.Strings(names)
    rows := make([]string, 0, len(names))
    for _, name := range names { rows = append(rows, name+":"+strconv.Itoa(inventory.stock[name])) }
    return strings.Join(rows, " ")
}

main.go

package main
import ("bufio"; "fmt"; "os")
func main() {
    input := bufio.NewReader(os.Stdin)
    inventory := NewInventory()
    accepted := 0
    for {
        var command, name string
        var count int
        if _, err := fmt.Fscan(input, &command, &name, &count); err != nil { break }
        var ok bool
        if command == "add" { ok = inventory.Add(name, count) } else { ok = inventory.Take(name, count) }
        if ok { accepted++ }
    }
    report := inventory.Report()
    fmt.Print(accepted)
    if report != "" { fmt.Print(" ", report) }
    fmt.Println()
}

Implementa le API Swift in Inventory.swift, Functions.swift. Mantieni il driver fornito in main.swift.

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 TEST DELL'API PUBBLICA
let apiOK = apiChecks(input)
// FINE DEI TEST DELL'API PUBBLICA
if apiOK { print(solve(input)) } else { print("API mismatch") }

Tutte le lezioni di Swift per sviluppatori Go

Esercitati da solo: Playground Swift