Port: Inventory Commands
Lesson 47 of 48 in Coddy's Swift for Lua Developers course.
Challenge
MediumPort the Lua 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 Lua reference for the same input and output contract:
local function new_inventory()
local stock = {}
local inventory = {}
function inventory:quantity(name) return stock[name] or 0 end
function inventory:add(name, count)
if count <= 0 then return false end
stock[name] = self:quantity(name) + count
return true
end
function inventory:take(name, count)
local available = self:quantity(name)
if count <= 0 or count > available then return false end
stock[name] = available - count
return true
end
function inventory:report()
local names, parts = {}, {}
for name in pairs(stock) do names[#names + 1] = name end
table.sort(names)
for _, name in ipairs(names) do parts[#parts + 1] = name .. ":" .. stock[name] end
return table.concat(parts, " ")
end
return inventory
end
local function solve(input)
local tokens = {}
for token in input:gmatch("%S+") do tokens[#tokens + 1] = token end
local inventory, accepted = new_inventory(), 0
for i = 1, #tokens, 3 do
local name, count = tokens[i + 1], tonumber(tokens[i + 2])
local ok
if tokens[i] == "add" then ok = inventory:add(name, count)
else ok = inventory:take(name, count) end
if ok then accepted = accepted + 1 end
end
local report = inventory:report()
return tostring(accepted) .. (report == "" and "" or " " .. report)
end
print(solve(io.read("*a")))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 Lua 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