Problem overview
The last version of Report Card summarises a whole class. Given a slice of scores, the program prints the highest score, the lowest score and the average, rounded down:
scores := []int{92, 78, 85, 67, 74, 88, 91, 58}
The scores add up to 633 and there are 8 of them, so the average is 633 / 8 = 79.125, which becomes 79 with integer division. The output is:
Highest: 92
Lowest: 58
Average: 79
Approach: one pass, three running values
Go has no built-in function that returns the largest value of a slice, and none is needed. A single loop can keep all three answers up to date as it goes:
highest, the largest score seen so far;lowest, the smallest score seen so far;total, the sum of all scores seen so far.
The two extremes start at the first score, scores[0], which is by definition both the largest and the smallest of the one score seen so far. Starting them at fixed numbers such as 0 or 100 would break for scores outside that guess. After the loop, average is total / len(scores).
The loop looks at every score once, so the work grows in step with the length of the slice.
This table shows the three variables at the end of each pass over the starting scores:
Score s | highest | lowest | total |
|---|---|---|---|
| 92 | 92 | 92 | 92 |
| 78 | 92 | 78 | 170 |
| 85 | 92 | 78 | 255 |
| 67 | 92 | 67 | 322 |
| 74 | 92 | 67 | 396 |
| 88 | 92 | 67 | 484 |
| 91 | 92 | 67 | 575 |
| 58 | 92 | 58 | 633 |
The first pass compares 92 with itself, so nothing changes except total. The highest never moves again, because 92 is the first score and the largest. The lowest drops at 78, at 67 and finally at 58 in the last pass.
Step by step
- Create
highestasscores[0]. - Create
lowestasscores[0]too. - Create
totalas 0. A running sum begins at zero, before any score is counted. - Loop over the scores with
for _, s := range scores. The range gives an index and a value for each element, and the_discards the index. Write the closing brace right away. - Update the maximum. If
sis greater thanhighest, assign it tohighest. - Update the minimum. If
sis less thanlowest, assign it tolowest. This is a separateif, not anelse, because a score can be tested against both. - Add to the total, after both checks and outside the
ifs. Every score counts toward the sum, not just a new highest or lowest. - Compute the average after the loop:
total / len(scores). Both operands areint, so the fraction is dropped. - Print three lines, each with a label and a number converted by
strconv.Itoa.
The solution in Go
scores := []int{92, 78, 85, 67, 74, 88, 91, 58}
highest := scores[0]
lowest := scores[0]
total := 0
for _, s := range scores {
if s > highest {
highest = s
}
if s < lowest {
lowest = s
}
total += s
}
average := total / len(scores)
fmt.Println("Highest: " + strconv.Itoa(highest))
fmt.Println("Lowest: " + strconv.Itoa(lowest))
fmt.Println("Average: " + strconv.Itoa(average))
The code uses the fmt and strconv packages. The Go details to know:
rangegives the value as a copy.sis a copy of each element, which is fine here because the loop only reads it.- The blank identifier. Go refuses unused variables. If you wrote
for i, s := range scoresand never usedi, the code wouldn't compile._is the way to say that you ignore the index. :=infersint.scores[0]is anint, sohighestandlowestareint.total := 0is aninttoo, since an integer literal defaults toint.+=adds in place.total += smeanstotal = total + s.lenis anint. That is whytotal / len(scores)compiles with no conversion: both sides have the same type. Dividing by afloat64would need a conversion first.
Complexity
Time is O(n): the loop makes one pass over the n scores and does a constant amount of work for each. Space is O(1), since the program keeps only highest, lowest, total and average.
Edge cases and common mistakes
- An empty slice.
scores[0]panics withindex out of range [0] with length 0. The average would also divide by zero, which panics for integers in Go. The lesson's data is never empty. - One score. The loop compares the score with itself, nothing changes, and the three lines show that score three times. For
{70}the output is 70, 70 and 70. - Starting
highestat 0. It works for positive scores but fails for all-negative data. For{-10, -20, -5}, ahighestthat starts at 0 stays 0, which is not in the data. Starting atscores[0]gives the correct -5. - Truncation. The average of 99 and 100 is 99.5 and prints as 99. For negative totals Go truncates toward zero: the average of -10, -20 and -5 prints as -11, although the exact value is -11.67.
- Counting only the extremes. If
total += ssits inside one of theifblocks, the sum is wrong, and so is the average. - Dividing by a hard-coded 8. Use
len(scores), so the program keeps working when the slice changes.
Testing
- The starting scores print
Highest: 92,Lowest: 58andAverage: 79. {70}prints 70, 70, 70.{80, 80, 80}prints 80, 80, 80.{99, 100}prints highest 100, lowest 99 and average 99.{-10, -20, -5}prints highest -5, lowest -20 and average -11.
