A map of structs is a tiny in-memory database.
What to build
A program that keeps a shop's stock from a list of commands.
Requirements
- Read n, then n commands, one per line:
add NAME QTY PRICEadds QTY items; if the item exists its quantity grows and its price becomes PRICE. Print nothing.remove NAME QTYremoves QTY items. If the name is unknown printno such item NAME; if there are fewer than QTY items printnot enough NAME; otherwise reduce the stock and keep the item even when the quantity reaches 0.reportprints one lineNAME QTY x PRICE = VALUEper item in alphabetical order, thentotal VALUE, where the value of an item is QTY times PRICE.
Input
Line 1: n. Then n commands. Prices and quantities are whole numbers.
Output
Messages and reports as described.
Constraints
1 ≤ n ≤ 50; names are single words; 1 ≤ QTY ≤ 1000; 1 ≤ PRICE ≤ 10000.
Example
Input:
5
add pen 10 3
add book 2 20
remove pen 4
remove cup 1
report
Output:
no such item cup
book 2 x 20 = 40
pen 6 x 3 = 18
total 58
Why it works
The map finds an item by name and the struct keeps its quantity and price together. Structs in a map are copies, so the changed copy must be stored back with items[name] = item.
Examples
Example 1 · Input
5 add pen 10 3 add book 2 20 remove pen 4 remove cup 1 report
Expected output
no such item cup book 2 x 20 = 40 pen 6 x 3 = 18 total 58
Example 2 · Input
4 add a 1 1 remove a 2 remove a 1 report
Expected output
not enough a a 0 x 1 = 0 total 0
Hints
Hint 1
Use type Item struct { Qty, Price int } and a map[string]Item. To change an item, read it, change the copy and store it back.
Hint 2
For report, sort the names with sort.Strings and add up Qty * Price.
Solution
Show one correct solution (try it yourself first)
package main
import (
"fmt"
"sort"
)
type Item struct {
Qty, Price int
}
func main() {
var n int
fmt.Scan(&n)
items := make(map[string]Item)
for i := 0; i < n; i++ {
var cmd string
fmt.Scan(&cmd)
switch cmd {
case "add":
var name string
var qty, price int
fmt.Scan(&name, &qty, &price)
item := items[name]
item.Qty += qty
item.Price = price
items[name] = item
case "remove":
var name string
var qty int
fmt.Scan(&name, &qty)
item, ok := items[name]
if !ok {
fmt.Println("no such item", name)
} else if item.Qty < qty {
fmt.Println("not enough", name)
} else {
item.Qty -= qty
items[name] = item
}
case "report":
names := []string{}
for k := range items {
names = append(names, k)
}
sort.Strings(names)
total := 0
for _, k := range names {
it := items[k]
value := it.Qty * it.Price
total += value
fmt.Printf("%s %d x %d = %d\n", k, it.Qty, it.Price, value)
}
fmt.Println("total", total)
}
}
}