Problem overview
Version 5 stores the report card as a map from subject name to score:
grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}
The program prints each subject with its letter grade, in alphabetical order of the subjects. The scale is unchanged: 90 and above is A, 80s are B, 70s are C, 60s are D and the rest F. The expected output is:
English: C
History: D
Math: A
Science: B
Approach: a map has no order, so sort the keys
A Go map doesn't remember the order of its entries, and a for ... range over a map visits them in an order that can change from one run to the next. Printing straight from the map would give the right lines in an unpredictable order. The same program printed the subjects as [History Math English Science] in one run and as [English Science History Math] in another.
The fix has two parts. First collect the keys into a slice, which does have an order. Then sort the slice and walk it, looking up each score in the map by its key. The map holds the data, and the sorted slice decides the order.
Here is what the key slice looks like before and after sort.Strings, for a run in which the loop happened to collect the keys in this order:
before: [History Math English Science]
after: [English History Math Science]
Only the slice changes. The map itself is untouched, and each lookup grades[subject] still finds the right score, because the key is what identifies it. The separation is the idea of the lesson: the map is good at lookup by name, the slice is good at holding an order, and you need both to print in a fixed order.
Step by step
- Create the slice.
subjects := make([]string, 0, len(grades))makes an empty slice of strings with room reserved for one name per subject. The length is 0 and the capacity islen(grades). - Collect the keys.
for subject := range gradesgives the keys of the map, one per pass. The line that appends each key tosubjectsgoes inside this loop. - Sort.
sort.Strings(subjects)sorts the slice in place, alphabetically. - Walk the sorted slice.
for _, subject := range subjectsgives index and value for each element. The blank identifier_discards the index, which the loop doesn't need. - Look up the score.
score := grades[subject]reads the value stored under that key. - Declare
grade.var grade stringstarts as an empty string. - Run the ladder. Test 90, 80, 70 and 60 from the top with
ifandelse if, and finish with anelsefor"F". - Print. After the ladder, inside the loop, print the subject,
": "and the grade.
The solution in Go
grades := map[string]int{"Math": 92, "English": 78, "Science": 85, "History": 67}
subjects := make([]string, 0, len(grades))
for subject := range grades {
subjects = append(subjects, subject)
}
sort.Strings(subjects)
for _, subject := range subjects {
score := grades[subject]
var grade string
if score >= 90 {
grade = "A"
} else if score >= 80 {
grade = "B"
} else if score >= 70 {
grade = "C"
} else if score >= 60 {
grade = "D"
} else {
grade = "F"
}
fmt.Println(subject + ": " + grade)
}
The code uses the fmt and sort packages. The details worth knowing:
- Range over a map yields keys first. With one loop variable you get the key. With two,
for key, value := range m, you get both. The loop that collects keys needs only the keys. - Range over a slice yields the index first. That is why the second loop writes
_, subject. Writingfor subject := range subjectswould give the index, a number, and the lookupgrades[subject]wouldn't compile. makewith a capacity.make([]string, 0, n)avoids repeated reallocation while appending.subjects := []string{}would work too, only less efficiently.sort.Stringscompares byte by byte. Uppercase letters come before lowercase ones. For the keysart,Biology,chemistryandDancethe sorted order isBiology,Dance,art,chemistry. This lesson's subjects all start with a capital letter, so plain alphabetical order results.- A missing key gives the zero value.
grades["Art"]returns 0 and doesn't report an error. The two-value formscore, ok := grades["Art"]tells you whether the key exists. Here every looked-up key comes from the map itself, so the plain form is safe.
Complexity
With n subjects, collecting the keys is O(n), sorting is O(n log n) and the grading loop is O(n), since each map lookup takes constant time on average. The total is O(n log n). The extra space is the subjects slice, O(n).
Edge cases and common mistakes
- Skipping the sort. The output may happen to look right on one run and be in another order the next time. The lesson's tests need the alphabetical order every time.
- Sorting the map. A map can't be sorted. Only the slice of keys can.
- Mixed case. Subjects such as
artandDancesort with all capitals first. With the data in this lesson that doesn't arise. - An empty map. The key slice stays empty, the loops don't run and nothing is printed.
- Boundary scores. A subject scoring exactly 60 gets D, and 59 gets F. With the map
art: 95, Biology: 59, chemistry: 60, Dance: 100the output isBiology: F,Dance: A,art: Aandchemistry: D.
Testing
- The starting map prints the four lines
English: C,History: D,Math: AandScience: B, in that order, on every run. - An empty map prints nothing.
