Problem overview
The cart has five items in parallel slices: items, prices and categories. Each item has a name, a price and a category such as Food or Clothes. The program adds up the prices per category and prints one line for each category, sorted alphabetically by name:
Clothes: $65
Food: $6
The shirt (25) and the pants (40) are clothes, giving 65. The apple (2), the bread (3) and the banana (1) are food, giving 6. Clothes comes first because C sorts before F, even though the first item in the cart is food.
Approach: accumulate in a map, then sort the keys
The categories are not known in advance, and one category can show up many times, in any order. A map from category to total handles this: for each item, add its price to the entry for its category.
The first item of a new category has no entry yet. In Go, reading a missing key from a map[string]int gives 0, so totals[cat] + prices[i] works on the first item too, with no special case.
The second problem is order. Go deliberately makes map iteration order random, so ranging over the map directly would print the categories in an order that can change from run to run. The fix is to copy the keys into a slice, sort the slice, and build the lines by walking the sorted slice and looking each total up in the map.
Step by step
- Create the map.
totals := map[string]int{}is empty, with string keys (categories) and int values (running totals). - Loop over the positions with
for i := range items. The sameiselects the matching price and category from the parallel slices. - Read the category.
cat := categories[i]gives the category of the current item. - Update the total.
totals[cat] = totals[cat] + prices[i]reads the current total (0 if the category is new), adds the price and stores the sum back. - Create the empty
linesslice for the output rows. - Create
keys.make([]string, 0, len(totals))builds a slice with length 0 and room reserved for as many strings as the map has keys. The capacity only avoids regrowing; the slice is still empty. - Collect the categories.
for cat := range totalsranges over a map; with one variable it yields the keys, in no fixed order. - Append each key to
keys, storing the result ofappendback inkeys. - Sort the keys with
sort.Strings(keys). It rearranges the slice in place and returns nothing. - Loop over the sorted keys.
for _, cat := range keysgives an index and a value; the blank identifier_discards the index, which is not needed. - Append a row per category: the category,
": $"and the total from the map, converted withstrconv.Itoa. - Join and print.
strings.Join(lines, "\n")puts a newline between rows only, andfmt.Printlnprints the result.
The solution in Go
items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
prices := []int{2, 3, 25, 1, 40}
categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}
totals := map[string]int{}
for i := range items {
cat := categories[i]
totals[cat] = totals[cat] + prices[i]
}
lines := []string{}
keys := make([]string, 0, len(totals))
for cat := range totals {
keys = append(keys, cat)
}
sort.Strings(keys)
for _, cat := range keys {
lines = append(lines, cat + ": $" + strconv.Itoa(totals[cat]))
}
result := strings.Join(lines, "\n")
fmt.Println(result)
Go details worth knowing here:
- Printing a map directly.
fmt.Println(totals)showsmap[Clothes:65 Food:6]. Thefmtpackage happens to print maps with their keys sorted, but that is formatting, not a property of the map. Looping over a map yourself gives no order, which is why this lesson sorts the keys. - Reusing the name
cat. The firstcatbelongs to the first loop body, the second to therange totalsloop, and the third to the loop overkeys. Each lives only inside its own loop, so there is no clash. - Imports. The program uses
fmt,sort,strconvandstrings. An unused import is a compile error in Go, as is an unused variable. sort.Stringscompares bytes. Uppercase letters sort before lowercase ones, so"Food"sorts before"food", and a category that starts with a capital comes before every category that starts with a lowercase letter.- Maps start empty with
map[string]int{}. Declaringvar totals map[string]intgives a nil map, which can be read but panics when you write to it.
Edge cases and common mistakes
- Skipping the sort. Ranging over
totalsto build the lines gives the right numbers in an unpredictable order, so the lesson's tests would pass on some runs and fail on others. - Different capitalization. Categories
foodandFoodare two keys. For items with those categories and prices 1 and 2, the output isFood: $2thenfood: $1. - An empty cart. The map is empty,
linesstays empty, andstrings.Joinreturns an empty string, so a blank line is printed. - Writing the sum with a check for missing keys. An
ifthat tests whether the key exists before adding is unnecessary here, since the zero value already starts each total at 0. - Using
len(totals)as the length.make([]string, len(totals))would create a slice that already holds empty strings, and appending to it would put the categories after them. The reference uses length 0 and the map size as capacity.
Testing
- The starting cart prints
Clothes: $65andFood: $6. - A single item, a lamp at 18 in
Home, printsHome: $18. - Prices 1, 2 and 3 with categories
food,FoodandClothesprintClothes: $3,Food: $2andfood: $1.
