Menu
Coddy logo textTech

Receive Stock

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 56 of 63.

Build an Inventory program that receives and sells stock, checks quantities and produces reports. Each stage extends the same command processor. Parse command fields, validate quantities before changing the map, and return one response per command. Invalid input must leave stock unchanged.

val fields = "ADD|pen|3".split("|")
challenge icon

Challenge

Hard

Complete 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. Support ADD|item|quantity: add a valid amount to that item's stock, initially zero, and reply added. Adding zero still creates the item. 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> {
    // Write your solution here.
    return emptyList()
}
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

Practice on your own: Kotlin playground