Lesson 20 of 38 · Slices & Maps
Boss Battle: The Hoarding Dragon (Go Slices and Maps Challenge)
The Hoarding Dragon blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Beneath the Gopher Isles, the Hoarding Dragon sleeps on a mountain of treasure that it counts in its dreams. One coin out of place and it wakes — so count, rank, merge and pack its hoard with Go slices and maps, without disturbing a single item, and slip past while it snores.
Battle plan
This fight uses everything from the chapter:
- Counting:
counts[item]++works on a fresh map because missing keys read as0. Create it withmake— a nil map panics on the first write. - Deterministic ranking: map iteration order is random, so copy the keys into a slice and sort it with a comparison that never ties: first by count, then alphabetically.
- Leave the hoard untouched: maps are references, so writing into a parameter changes the caller's map. Build results in new maps and slices.
- Copies, not views:
items[start:end]shares the array ofitems. When the result must be independent, copy it withslices.Clone. - Bounds: clamp
nand slice ends so you never index pastlen(s).
The starter only imports fmt. Add slices, cmp, sort or strings to the imports as you need them, and press Run at any time: main prints what your functions return so far.
Assignment
Write four functions:
CountLoot(items []string) map[string]intreturns how many times each item appears. For empty or nilitems, return an empty map that the caller can write to — not a nil map.TopLoot(counts map[string]int, n int) []stringreturns the item names ordered by count, highest first; names with the same count are ordered alphabetically. Return at mostnnames: all of them ifnis larger than the number of items, and an empty slice ifn <= 0.MergeHoards(a, b map[string]int) map[string]intreturns a new map in which every item's count is the sum of its counts inaandb. Neitheranorbmay change, and either may be nil.ChunkLoot(items []string, size int) [][]stringpacks the items, in order, into bags ofsizeitems; the last bag may be smaller. Ifsize <= 0, return nil. Every bag must be a copy: changing a bag must never changeitems.
hoard := []string{"gold", "gem", "gold", "crown", "gold", "gem"}
counts := CountLoot(hoard) // map[crown:1 gem:2 gold:3]
TopLoot(counts, 2) // [gold gem]
ChunkLoot(hoard, 4) // [[gold gem gold crown] [gold gem]]
a := map[string]int{"gold": 2, "gem": 1}
b := map[string]int{"gold": 3}
MergeHoards(a, b) // map[gem:1 gold:5]Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .