Menu
Coddy logo textTech

Recap - Inventory

Part of the Logic & Flow section of Coddy's Swift journey — lesson 17 of 56.

challenge icon

Challenge

Medium

You're tracking shop inventory. Read a single line of input: a comma-separated list of operations against an initially-empty [String: Int] called stock. Each operation is one of:

  • in:<item>:<qty> add quantity to the item (use the default-subscript pattern)
  • out:<item>:<qty> subtract quantity. If the resulting quantity is 0 or negative, remove the key entirely.

After applying every op, print:

  1. One line per remaining item, sorted alphabetically, in the format <item>: <qty>
  2. Total units: <n> across every remaining value

For input in:apple:5,in:bread:2,out:apple:3,in:apple:4,out:bread:5, the output is:

apple: 6
Total units: 6

Try it yourself

let ops = readLine()!.components(separatedBy: ",")
var stock: [String: Int] = [:]

// TODO: parse each op as kind:item:qty; in adds, out subtracts;
// remove keys whose qty drops to <= 0; print sorted lines + total

All lessons in Logic & Flow