Problem overview
The last version of the report card looks at a whole class. A vector holds eight scores: 92, 78, 85, 67, 74, 88, 91 and 58. The program prints the highest score, the lowest score and the average, rounded down:
Highest: 92
Lowest: 58
Average: 79
The scores add up to 633, and 633 divided by 8 is 79.125. Integer division drops the part after the point, so the average is 79. The previous versions graded individual scores; this one summarizes a list of them.
Approach: iterators for the extremes, a loop for the sum
The highest and lowest scores come from iterator methods. scores.iter() walks the vector, max() returns the biggest element and min() the smallest. Each returns an Option, because an empty vector has no biggest element, so unwrap() takes the value out of the Some.
The average needs a sum. A running total starts at 0, and a loop adds each score to it. After the loop, the total divided by the number of scores, scores.len(), is the average. Both numbers are integers, so the division truncates.
That makes three separate passes over the data: one for max, one for min and one for the sum. For a list this size the cost is irrelevant, and each pass says exactly what it does.
Step by step
- Create
scoreswithvec!and the eight values in the given order. - Find
highestwithscores.iter().max().unwrap(). - Find
lowestin the same way withmin(). - Create
totalaslet mut, starting at 0. A running total begins at zero, before any score is counted. - Loop over the scores with
for s in &scores. The&borrows the vector, so it is still available after the loop. - Add each score to
totalinside the loop. - Compute
averageafter the loop astotal / scores.len(). - Print the three lines in the order Highest, Lowest, Average, each with a
{}placeholder.
The solution in Rust
let mut scores = vec![92, 78, 85, 67, 74, 88, 91, 58];
let mut highest = scores.iter().max().unwrap();
let mut lowest = scores.iter().min().unwrap();
let mut total = 0;
for s in &scores {
total += s;
}
let mut average = total / scores.len();
println!("Highest: {}", highest);
println!("Lowest: {}", lowest);
println!("Average: {}", average);
Rust details worth knowing:
- Extra
muts. Onlytotalchanges after it is created. The other variables are markedmutin the lesson's code, and the compiler answers withvariable does not need to be mutablewarnings. They are only warnings, and the program prints the expected three lines. - The element type is
usize. The divisiontotal / scores.len()needs both sides to be the same type, andlen()returns ausize. Rust therefore infersusizefortotaland for the elements ofscores. One result is that a negative score doesn't compile:vec![92, -5]in this program fails withthe trait bound `usize: Neg` is not satisfied. - References to elements.
max()andmin()oniter()returnOption<&usize>, sohighestandlowestare references into the vector.println!prints through the reference, so the output is the plain number. For the same reasonsin the loop is a&usize, andtotal += scompiles because Rust can add a reference to an integer in place. unwrap()panics onNone. It is safe here because the vector has eight elements.- Integer division.
633 / 8gives 79 in integer arithmetic. The number 79.125 would needf64values.
Complexity
Time: O(n) for n scores. max(), min() and the summing loop each walk the vector once, which is three passes, and three passes are still O(n). Space: O(1) extra, because the program keeps a few single values, and the references point into the existing vector.
Edge cases and common mistakes
- An empty vector.
max()returnsNone, sounwrap()panics withcalled `Option::unwrap()` on a `None` value. Past that point, dividing byscores.len(), which is 0, would panic withattempt to divide by zero. - One score. A vector holding only 70 gives a highest, lowest and average of 70.
- Averages that don't divide evenly. Scores 90 and 91 have a total of 181, and the average is 90. The remainder is dropped, not rounded to the nearest whole number.
- Starting the total at something other than 0. Any other starting value would be added to every average.
- Dividing inside the loop. The division must come after the loop, once the total is complete.
- Forgetting the
&.for s in scoresmoves the vector into the loop, and the later call toscores.len()is then an error.
Testing
- The lesson's data prints
Highest: 92,Lowest: 58andAverage: 79. - A single score of 70 prints 70 on all three lines.
- Scores 90 and 91 print
Highest: 91,Lowest: 90andAverage: 90.
