Low Stock Alerts
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 60 of 63.
Challenge
HardComplete runInventory with parameters commands: List<String>. Build an inventory that starts empty for each function call. Each command is one string with fields separated by |. Item names are lowercase ASCII words. There are at most 100 commands. Split each command on the literal separator; commands always have the correct number of fields for their operation. Return one reply per command. Quantities are trimmed before parsing; valid amounts are between 0 and 1000. Invalid numeric text, out-of-Int-range text, negative amounts or amounts above 1000 produce invalid with no state change. Keep everything you wrote in the previous steps, including every earlier command and reply. Support ADD|item|quantity: add a valid amount to that item's stock, initially zero, and reply added. Adding zero still creates the item. Add GET|item: reply with its quantity as a string, or 0 when the item is absent. Add SELL|item|quantity: first validate the amount using the same rules as ADD. For a valid amount, reply insufficient if available stock is smaller; otherwise subtract it and reply sold. An absent item has zero available. Selling zero succeeds without creating a missing item. Keep zero-stock existing items. Add REPORT: reply with all saved entries as item=quantity separated by ;, sorted alphabetically by item. Include zero-stock entries. An empty inventory produces empty. REPORT has no argument fields. Add LOW|threshold: validate threshold using the same numeric rules as amounts. Reply invalid on invalid input. Otherwise reply with saved item names whose quantity is strictly below threshold, sorted alphabetically and separated by ;, or none if none qualify. LOW does not change stock. Input uses only the operations supported at this step.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type List<String>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun runInventory(commands: List<String>): List<String> {
val stock = mutableMapOf<String, Int>()
val replies = mutableListOf<String>()
for (command in commands) {
val parts = command.split("|")
val operation = parts[0]
val item = if (parts.size > 1) parts[1] else ""
when (operation) {
"ADD" -> {
val amount = parts[2].trim().toIntOrNull()
if (amount == null || amount !in 0..1000) replies.add("invalid")
else {
stock[item] = (stock[item] ?: 0) + amount
replies.add("added")
}
}
"GET" -> replies.add((stock[item] ?: 0).toString())
"SELL" -> {
val amount = parts[2].trim().toIntOrNull()
val available = stock[item] ?: 0
if (amount == null || amount !in 0..1000) replies.add("invalid")
else if (amount > available) replies.add("insufficient")
else {
if (stock.containsKey(item)) stock[item] = available - amount
replies.add("sold")
}
}
"REPORT" -> {
if (stock.isEmpty()) replies.add("empty")
else replies.add(stock.keys.sorted().map { "$it=${stock[it]}" }.joinToString(";"))
}
}
}
return replies
}
fun main() {
val commandsCount = readln().toInt()
val commands = mutableListOf<String>()
for (i0 in 0 until commandsCount) {
val commandsItem = readLine().orEmpty()
commands.add(commandsItem)
}
println(runInventory(commands))
}All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind ContactsPractice on your own: Kotlin playground