Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for R Developers course.
Challenge
MediumPort the R reference into Swift. Implement Inventory() with add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int, and report() -> String. Add accepts only positive counts. Take accepts only positive counts at most current stock. Rejections preserve all state; unknown quantities are zero. Successful takes retain zero-stock entries. Report all stored names ascending as name:quantity separated by spaces. Input contains 0 through 40 command triples: add name count or take name count. Names are lowercase ASCII words up to 10 letters, counts -10 through 100. Output successful command count, followed by a space and report only when nonempty.
Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.
Complete R reference for the same input and output contract:
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 = "")Your code goes in Inventory.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.
Try it yourself
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)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
All lessons in Swift for R Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground