Today everything from the week comes together in one program: an order ledger that reserves stock for orders. It reads commands, one per line, from standard input:
stock ITEM QUANTITY adds stock to an item.
order ID ITEM:QUANTITY ... reserves one to eight lines, all or none.
cancel ID returns an open order's stock.
report prints the whole ledger as canonical JSON.
Item names use 1 to 20 lowercase letters, digits or hyphens. Quantities are whole numbers from 1 to 1000, and no item can ever hold more than 10000. An order ID sent again with the same lines, in any order, is a retry: it is recognized and reserves nothing more. Reusing an ID with different lines, or after a cancel, is rejected. A rejected command is reported with its line number and skipped, and processing continues.
The program reads all its input first. If any line is longer than 200 bytes or there are more than 1000 commands, it stops with an error and applies nothing. It then parses the commands on four goroutines and applies them one at a time in input order, so the output never depends on scheduling.
Predict and run
Read the sample input in the box under the editor before you run it. Which commands are rejected, and why? What does the final report show for each item and order?
Run the order ledgerGopackage main
import (
"context"
"fmt"
"os"
)
func main() {
if err := run(context.Background(), os.Stdin, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
package main
import (
"errors"
"fmt"
)
// Limits that bound every input before it can change the ledger.
const (
maxQuantity = 1000 // per stock command or order line
maxStock = 10000 // per item, at any time
maxOrderLines = 8
maxLineBytes = 200
maxCommands = 1000
)
var (
errItem = errors.New("item names use 1-20 lowercase letters, digits or hyphens")
errOrderID = errors.New("order IDs use 1-12 letters or digits")
errQuantity = errors.New("quantity must be 1-1000")
errDuplicateItem = errors.New("item is listed twice")
errOrderLines = errors.New("orders take 1-8 lines")
errCapacity = errors.New("stock would exceed 10000")
errConflict = errors.New("order ID reused with different lines")
errUnknownOrder = errors.New("order not found")
errCancelled = errors.New("order is cancelled")
errLineTooLong = errors.New("line is longer than 200 bytes")
errTooManyCommands = errors.New("input has more than 1000 commands")
)
// Line is one item and quantity in a stock command or an order.
type Line struct {
Item string
Quantity int
}
// ShortageError reports the first item an order could not reserve.
type ShortageError struct {
Item string
Have int
Need int
}
func (e *ShortageError) Error() string {
return fmt.Sprintf("not enough %s: have %d, need %d", e.Item, e.Have, e.Need)
}
package main
import (
"cmp"
"errors"
"fmt"
"slices"
"strconv"
"strings"
)
// Command is one parsed input line.
type Command struct {
Verb string
ID string // the order ID, for order and cancel
Lines []Line // one line for stock, sorted by item for order
}
func validItem(name string) bool {
if len(name) < 1 || len(name) > 20 {
return false
}
for _, r := range name {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
return false
}
}
return true
}
func validOrderID(id string) bool {
if len(id) < 1 || len(id) > 12 {
return false
}
for _, r := range id {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') {
return false
}
}
return true
}
func parseQuantity(text string) (int, error) {
n, err := strconv.Atoi(text)
if err != nil || n < 1 || n > maxQuantity {
return 0, errQuantity
}
return n, nil
}
// parseOrder reports every bad entry at once, joined into one error.
func parseOrder(id string, entries []string) (Command, error) {
if !validOrderID(id) {
return Command{}, fmt.Errorf("%q: %w", id, errOrderID)
}
if len(entries) < 1 || len(entries) > maxOrderLines {
return Command{}, fmt.Errorf("order %s: %w", id, errOrderLines)
}
var problems []error
seen := make(map[string]bool)
lines := make([]Line, 0, len(entries))
for _, entry := range entries {
item, quantity, ok := strings.Cut(entry, ":")
if !ok {
problems = append(problems, fmt.Errorf("%q: use ITEM:QUANTITY", entry))
continue
}
if !validItem(item) {
problems = append(problems, fmt.Errorf("%q: %w", item, errItem))
continue
}
if seen[item] {
problems = append(problems, fmt.Errorf("%q: %w", item, errDuplicateItem))
continue
}
seen[item] = true
n, err := parseQuantity(quantity)
if err != nil {
problems = append(problems, fmt.Errorf("%q: %w", item, err))
continue
}
lines = append(lines, Line{Item: item, Quantity: n})
}
if err := errors.Join(problems...); err != nil {
return Command{}, fmt.Errorf("order %s: %w", id, err)
}
// Sorting makes the line order irrelevant, so a reordered retry still matches.
slices.SortFunc(lines, func(a, b Line) int { return cmp.Compare(a.Item, b.Item) })
return Command{Verb: "order", ID: id, Lines: lines}, nil
}
func parseCommand(text string) (Command, error) {
fields := strings.Fields(text)
verb, args := fields[0], fields[1:]
switch verb {
case "stock":
if len(args) != 2 {
return Command{}, errors.New("use stock ITEM QUANTITY")
}
if !validItem(args[0]) {
return Command{}, fmt.Errorf("%q: %w", args[0], errItem)
}
n, err := parseQuantity(args[1])
if err != nil {
return Command{}, err
}
return Command{Verb: verb, Lines: []Line{{Item: args[0], Quantity: n}}}, nil
case "order":
if len(args) == 0 {
return Command{}, errors.New("use order ID ITEM:QUANTITY ...")
}
return parseOrder(args[0], args[1:])
case "cancel":
if len(args) != 1 || !validOrderID(args[0]) {
return Command{}, errors.New("use cancel ID")
}
return Command{Verb: verb, ID: args[0]}, nil
case "report":
if len(args) != 0 {
return Command{}, errors.New("report takes no arguments")
}
return Command{Verb: verb}, nil
default:
return Command{}, fmt.Errorf("unknown command %q", verb)
}
}
package main
import (
"fmt"
"iter"
"maps"
"slices"
)
type order struct {
lines []Line
cancelled bool
}
// Ledger tracks stock and the orders that reserved it. Every method either
// applies its whole change or returns an error and changes nothing.
type Ledger struct {
stock map[string]int
orders map[string]order
}
func NewLedger() *Ledger {
return &Ledger{stock: make(map[string]int), orders: make(map[string]order)}
}
// addStock returns have+n, or errCapacity if the sum would pass maxStock.
// Comparing with maxStock-have cannot overflow, unlike computing have+n first.
func addStock(have, n int) (int, error) {
if n > maxStock-have {
return 0, errCapacity
}
return have + n, nil
}
// Stock adds quantity to an item and returns its new total.
func (l *Ledger) Stock(item string, quantity int) (int, error) {
total, err := addStock(l.stock[item], quantity)
if err != nil {
return 0, fmt.Errorf("stock %s: %w", item, err)
}
l.stock[item] = total
return total, nil
}
type Outcome int
const (
Reserved Outcome = iota
Replayed
)
// Order reserves every line or none. Sending the same order ID with the same
// lines again is a retry: it is recognized and reserves nothing more.
func (l *Ledger) Order(id string, lines []Line) (Outcome, error) {
if previous, exists := l.orders[id]; exists {
if previous.cancelled {
return 0, fmt.Errorf("order %s: %w", id, errCancelled)
}
if !slices.Equal(previous.lines, lines) {
return 0, fmt.Errorf("order %s: %w", id, errConflict)
}
return Replayed, nil
}
staged := maps.Clone(l.stock)
for _, line := range lines {
have := staged[line.Item]
if line.Quantity > have {
return 0, fmt.Errorf("order %s: %w", id, &ShortageError{Item: line.Item, Have: have, Need: line.Quantity})
}
staged[line.Item] = have - line.Quantity
}
l.stock = staged
l.orders[id] = order{lines: slices.Clone(lines)}
return Reserved, nil
}
// Cancel returns an open order's stock. It fails without changes if that
// would take any item past maxStock.
func (l *Ledger) Cancel(id string) error {
previous, exists := l.orders[id]
if !exists {
return fmt.Errorf("order %s: %w", id, errUnknownOrder)
}
if previous.cancelled {
return fmt.Errorf("order %s: %w", id, errCancelled)
}
staged := maps.Clone(l.stock)
for _, line := range previous.lines {
total, err := addStock(staged[line.Item], line.Quantity)
if err != nil {
return fmt.Errorf("cancel %s: %s: %w", id, line.Item, err)
}
staged[line.Item] = total
}
l.stock = staged
previous.cancelled = true
l.orders[id] = previous
return nil
}
// Items yields each item and its quantity in name order.
func (l *Ledger) Items() iter.Seq2[string, int] {
return func(yield func(string, int) bool) {
for _, item := range slices.Sorted(maps.Keys(l.stock)) {
if !yield(item, l.stock[item]) {
return
}
}
}
}
// Snapshot is the ledger's state in a form encoding/json writes canonically:
// map keys come out sorted, so equal ledgers produce identical bytes.
type Snapshot struct {
Stock map[string]int `json:"stock"`
Orders map[string]string `json:"orders"`
}
func (l *Ledger) Snapshot() Snapshot {
orders := make(map[string]string, len(l.orders))
for id, o := range l.orders {
orders[id] = "open"
if o.cancelled {
orders[id] = "cancelled"
}
}
return Snapshot{Stock: maps.Clone(l.stock), Orders: orders}
}
package main
import (
"context"
"sync"
)
// mapConcurrent applies f to every item on up to workers goroutines and
// returns the results in input order. If ctx is cancelled first, it returns
// ctx.Err() and no results.
func mapConcurrent[T, R any](ctx context.Context, items []T, workers int, f func(T) R) ([]R, error) {
workers = max(1, min(workers, len(items)))
results := make([]R, len(items))
jobs := make(chan int)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results[i] = f(items[i]) // each index has exactly one writer
}
}()
}
send:
for i := range items {
select {
case jobs <- i:
case <-ctx.Done():
break send
}
}
close(jobs)
wg.Wait()
if err := ctx.Err(); err != nil {
return nil, err
}
return results, nil
}
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"iter"
"strings"
)
const workers = 4
type numbered struct {
line int
text string
}
type parsed struct {
line int
cmd Command
err error
}
// numberedLines yields every line with its 1-based number. Check
// scanner.Err after the loop.
func numberedLines(scanner *bufio.Scanner) iter.Seq2[int, string] {
return func(yield func(int, string) bool) {
for number := 1; scanner.Scan(); number++ {
if !yield(number, scanner.Text()) {
return
}
}
}
}
// readCommands reads all input before anything runs, so input that breaks a
// limit is rejected as a whole.
func readCommands(r io.Reader) ([]numbered, error) {
scanner := bufio.NewScanner(r)
// A scanner returns lines shorter than its buffer, with or without a final
// newline. Both the initial capacity and the maximum count, so setting
// both to one byte over the limit enforces the limit exactly.
scanner.Buffer(make([]byte, 0, maxLineBytes+1), maxLineBytes+1)
var input []numbered
last := 0
for number, text := range numberedLines(scanner) {
last = number
text = strings.TrimSpace(text)
if text == "" {
continue
}
if len(input) == maxCommands {
return nil, fmt.Errorf("line %d: %w", number, errTooManyCommands)
}
input = append(input, numbered{line: number, text: text})
}
if err := scanner.Err(); err != nil {
if errors.Is(err, bufio.ErrTooLong) {
return nil, fmt.Errorf("line %d: %w", last+1, errLineTooLong)
}
return nil, err
}
return input, nil
}
func execute(l *Ledger, cmd Command) (string, error) {
switch cmd.Verb {
case "stock":
line := cmd.Lines[0]
total, err := l.Stock(line.Item, line.Quantity)
if err != nil {
return "", err
}
return fmt.Sprintf("Stocked %s: %d", line.Item, total), nil
case "order":
outcome, err := l.Order(cmd.ID, cmd.Lines)
if err != nil {
return "", err
}
if outcome == Replayed {
return "Replayed " + cmd.ID, nil
}
return "Reserved " + cmd.ID, nil
case "cancel":
if err := l.Cancel(cmd.ID); err != nil {
return "", err
}
return "Cancelled " + cmd.ID, nil
case "report":
data, err := json.Marshal(l.Snapshot())
if err != nil {
return "", err
}
return string(data), nil
default:
return "", fmt.Errorf("unknown command %q", cmd.Verb)
}
}
// run parses every command concurrently, then applies them one at a time in
// input order. Rejected commands are reported and skipped. Read, write and
// cancellation failures end the run.
func run(ctx context.Context, r io.Reader, w io.Writer) (err error) {
input, err := readCommands(r)
if err != nil {
return fmt.Errorf("read input: %w", err)
}
commands, err := mapConcurrent(ctx, input, workers, func(n numbered) parsed {
cmd, err := parseCommand(n.text)
return parsed{line: n.line, cmd: cmd, err: err}
})
if err != nil {
return err
}
out := bufio.NewWriter(w)
defer func() {
if flushErr := out.Flush(); flushErr != nil && err == nil {
err = fmt.Errorf("write output: %w", flushErr)
}
}()
ledger := NewLedger()
for _, p := range commands {
text, cmdErr := "", p.err
if cmdErr == nil {
text, cmdErr = execute(ledger, p.cmd)
}
if cmdErr != nil {
// errors.Join separates problems with newlines; keep one line per command.
text = fmt.Sprintf("Line %d: %s", p.line, strings.ReplaceAll(cmdErr.Error(), "\n", "; "))
}
if _, err := fmt.Fprintln(out, text); err != nil {
return fmt.Errorf("write output: %w", err)
}
}
return nil
}
stock tent 5
stock drill 2
order A1 tent:2 drill:1
order A1 drill:1 tent:2
order A2 tent:4
order A1 tent:3
cancel A1
order A3 lamp:0 Tent:1
report
Check your prediction
Text
Stocked tent: 5Stocked drill: 2Reserved A1Replayed A1Line 6: order A2: not enough tent: have 3, need 4Line 7: order A1: order ID reused with different linesCancelled A1Line 9: order A3: "lamp": quantity must be 1-1000; "Tent": item names use 1-20 lowercase letters, digits or hyphens{"stock":{"drill":2,"tent":5},"orders":{"A1":"cancelled"}}
Where the week's ideas appear
Each line of that output exercises something you built this week:
Line 5, Replayed A1. The retry lists its lines in another order. The parser sorted both copies, so they compare equal (Day 4).
Line 6. The shortage is a *ShortageError with the item and both numbers as fields, wrapped with the order ID (Day 2). Nothing was reserved, because the order was staged on a copy (Day 4).
Line 9. Both bad entries are reported at once through errors.Join, printed on one line (Day 2).
The report. It is a canonical JSON snapshot. Its map keys are sorted, so equal ledgers print identical text (Day 6).
Behind it all. The lines come from an iterator over a bounded scanner (Day 3), and the parsing runs on a generic, cancellable worker pool (Days 1 and 5).
Line 3, the blank line, produced no output, but it still counts, which is why the later messages say line 6, 7 and 9.
Exercise
Predict three edits
Make each change to the input on its own, predict the output, then run it. First, add order A1 drill:1 tent:2 after the cancel. Second, change the stock tent 5 line to stock tent 4. Third, add a line of 201 characters anywhere.
Hint 1: the idea
Each change hits a different rule: replay after cancel, a shortage that appears earlier, and the input limit that applies before any command runs.
Hint 2: a first step
For the second edit, follow the tent stock line by line: 4, then A1 takes 2. How many are left when A2 asks for 4, and when A1 is cancelled?
Worked solution
The first edit adds Line 9: order A1: order is cancelled, and the later line numbers move down by one. A cancelled ID stays used, so the ledger never confuses an old order with a new one.
The second edit changes three lines. The first becomes Stocked tent: 4, A2's shortage message becomes have 2, need 4, and the report shows "tent":4. A1 still fits, and every other line stays the same.
The third edit prints nothing at all. The run fails with read input: line N: line is longer than 200 bytes, where N is the line you added, because the limits are checked while reading, before any command is applied.
Completion is saved in this browser only. It does not measure mastery.