Port: Comandi di inventario
Lezione 47 di 48 del corso Swift per sviluppatori R di Coddy.
Sfida
MedioPorta il riferimento in R 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 mantengono le voci con scorte pari a zero. Il 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 oppure take name count. I nomi sono parole in ASCII minuscole, lunghe al massimo 10 lettere; i conteggi vanno da -10 a 100. L'output contiene il numero di comandi completati, 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 con esattamente un newline. Tutte le operazioni numeriche restano entro i limiti di Int.
Riferimento completo in R per lo stesso contratto di input e output:
new_inventory <- function() {
stock <- list()
quantity <- function(name) {
value <- stock[[name]]
if (is.null(value)) 0L else value
}
add <- function(name, count) {
if (count <= 0L) return(FALSE)
stock[[name]] <<- quantity(name) + count
TRUE
}
take <- function(name, count) {
available <- quantity(name)
if (count <= 0L || count > available) return(FALSE)
stock[[name]] <<- available - count
TRUE
}
report <- function() {
keys <- sort(as.character(names(stock)), method = "radix")
parts <- vapply(keys, function(name) paste0(name, ":", stock[[name]]), character(1L))
paste(parts, collapse = " ")
}
list(quantity = quantity, add = add, take = take, report = report)
}
solve <- function(tokens) {
stock <- new_inventory()
accepted <- 0L
if (length(tokens) > 0L) {
for (i in seq.int(1L, length(tokens), by = 3L)) {
name <- tokens[[i + 1L]]
count <- as.integer(tokens[[i + 2L]])
ok <- if (tokens[[i]] == "add") stock$add(name, count) else stock$take(name, count)
if (ok) accepted <- accepted + 1L
}
}
report <- stock$report()
paste0(accepted, if (nzchar(report)) paste0(" ", report) else "")
}
tokens <- scan(file("stdin"), what = character(), quiet = TRUE)
cat(solve(tokens), "\n", sep = "")Il tuo codice va in Inventory.swift, Functions.swift. main.swift contiene il codice fornito per l'input e l'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 R
1Primi passi con Swift
Lavorare con i fileBinding e mutazioneNumeri e conversioneCondizioni booleaneRiepilogo: Fare Quote4Funzioni e array
Funzioni ed etichetteInout e accesso esclusivoTuple e risultati multipliGli array hanno la semantica di valoreRiepilogo: Gradini crescenti2Testo e decisioni
Stringhe e interpolazioneOptional e bindingGuard e uscita anticipataIf e valori di ramificazioneRiepilogo: Regole di ingressoEsercitati da solo: Playground Swift