Problem overview
Version 5 stores the scores in a map from subject name to score instead of two arrays. The starter code creates a scala.collection.mutable.TreeMap[String, Int] and fills it: Math is 92, English 78, Science 85 and History 67. The program prints each subject with its letter grade, in alphabetical order:
English: C
History: D
Math: A
Science: B
The grading scale is unchanged: 90 and above is A, 80 to 89 B, 70 to 79 C, 60 to 69 D, anything lower F.
Approach
A map stores key-value pairs and finds a value from its key. Here the keys are the subjects and the values are the scores. The program loops over the keys, looks up each score and runs the same ladder as before.
The order of the output is the interesting part. The subjects were inserted as Math, English, Science and History, but the output is alphabetical. That is the job of a TreeMap: it keeps its keys sorted, so walking over grades.keys visits English, History, Math and Science no matter how they were inserted. A hash-based map makes no promise about order, which is why the starter code chose a TreeMap.
Step by step
- Loop over the keys.
for (subject <- grades.keys)hands over one subject at a time, in sorted order. Close the brace right away. - Look up the score.
val score = grades(subject). Scala looks up a map with parentheses, as it indexes an array. - Declare
gradeas avarholding empty text. - Start the ladder with an
iffor 90 or more that sets"A". - Add the branch for 80 or more, which sets
"B". - Add the branch for 70 or more, which sets
"C". - Add the branch for 60 or more, which sets
"D". - Finish with
elsefor"F"and close the ladder. - Print the subject, a colon, a space and the grade, inside the loop.
The solution in Scala
val grades = scala.collection.mutable.TreeMap[String, Int]()
grades("Math") = 92
grades("English") = 78
grades("Science") = 85
grades("History") = 67
for (subject <- grades.keys) {
val score = grades(subject)
var grade = ""
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"
}
println(subject + ": " + grade)
}
What the loop visits
Walking over the sorted keys, each pass looks up one score and prints one grade:
subject | grades(subject) | printed |
|---|---|---|
| English | 78 | English: C |
| History | 67 | History: D |
| Math | 92 | Math: A |
| Science | 85 | Science: B |
The ladder itself is the same code as in the version for a list of students. Only the way the score is found changed: a key lookup replaces an index into an array, so there are no positions to keep in step.
Working with a mutable map
The statement writes grades("Math") = 92. On a mutable map that call adds the key if it is new and replaces the value if it already exists. Assigning grades("Math") = 50 later changes the stored score to 50 and leaves the size of the map at 4.
grades(subject) throws NoSuchElementException if the key is missing. For the message key not found: Music that is what a lookup of an absent subject gives. When a key might be missing, use grades.get("Music"), which returns an Option: Some(92) for Math and None for Music. grades.getOrElse("Music", 0) returns 0 instead. In this lesson every key comes from grades.keys, so the plain lookup is safe.
Printing the map itself shows the sorted order: TreeMap(English -> 78, History -> 67, Math -> 92, Science -> 85), and grades.keys is a SortedSet.
The price of keeping the keys sorted is a little speed. A mutable TreeMap is a balanced tree, so a lookup or an insertion takes about log n steps, where a hash map takes roughly constant time. For four subjects the difference is invisible, and the ordered output is worth more here.
Edge cases and common mistakes
- Uppercase before lowercase. A
TreeMap[String, Int]compares strings by character code, where every capital letter comes before every lowercase one. With the keys"Art","art"and"Biology", the order isArt,Biology,art. The lesson's four subjects all start with a capital, so they sort as expected. - An empty map. The loop body never runs and nothing is printed.
- Using a plain
HashMap. The grades would still be right, but the lines could come out in any order and the lesson's tests expect alphabetical output. - Losing a subject by reusing a key. Putting two scores under the same name keeps only the last one, because keys are unique.
- Boundary scores. Subjects with 55, 60 and 95 get F, D and A: a lower bound of 60 is inclusive, so 60 passes with a D.
Testing
Add a subject to the map and see where it lands: a new entry named Art appears first, before English, because the keys stay sorted. Change a score to 90 and the grade becomes A; change it to 59 and it becomes F. An empty map should print nothing at all.
Key takeaways
- A
TreeMapkeeps its keys sorted, so iterating over its keys gives alphabetical order. map(key)reads a value and throws if the key is absent;getgives anOption.- On a mutable map,
map(key) = valueadds or replaces an entry.
