Check Stock
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 57 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. 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")
}
}
}
}
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