Problem overview
Version 6 of the Report Card project computes statistics for a whole class. The array scores holds eight numbers, and the program prints three lines: the highest score, the lowest score and the average, rounded down to a whole number.
For the starting scores [92, 78, 85, 67, 74, 88, 91, 58] the highest is 92 and the lowest is 58. The scores add up to 633, and there are 8 of them. Divided exactly, 633 / 8 is 79.125, and rounding down gives 79:
Highest: 92
Lowest: 58
Average: 79
Approach: two library calls and one loop
The three values need different tools.
The highest and lowest come straight from Math.max and Math.min. Both accept any number of arguments and return the largest or smallest of them. They don't accept an array, though. scores is one value, so the array has to be spread into separate arguments with ...scores. Then Math.max(...scores) acts like Math.max(92, 78, 85, ...).
The average needs the sum of all scores first. A total variable starts at 0, and a loop adds each score to it. The sum is then divided by the count, scores.length, and rounded down with Math.floor. The division matters here: total / scores.length is 79.125, not 79, because number is a floating-point type and / keeps the fraction.
Because the average uses scores.length instead of the literal 8, it stays correct when the array has a different number of scores.
Step by step
- Find the highest. Create
highestas aconstof typenumber, set toMath.max(...scores). One call does the work, so no loop is needed. - Find the lowest with
Math.min(...scores)in aconstnamedlowest. It mirrors the previous step. - Start the sum. Declare
totalwithlet, typednumber, set to 0. It must beletbecause it changes with every score added. - Add the scores. Use
for (const s of scores)andtotal += s. The body is a single statement, so it fits on the same line as the loop header. - Compute the average. Create
averageas aconst:Math.floor(total / scores.length). Divide first, then round down. - Print three lines. Three
console.logcalls print"Highest: "withhighest,"Lowest: "withlowestand"Average: "withaverage, in that order.
The solution in TypeScript
const scores: number[] = [92, 78, 85, 67, 74, 88, 91, 58];
const highest: number = Math.max(...scores);
const lowest: number = Math.min(...scores);
let total: number = 0;
for (const s of scores) total += s;
const average: number = Math.floor(total / scores.length);
console.log("Highest: " + highest);
console.log("Lowest: " + lowest);
console.log("Average: " + average);
Details worth knowing:
- The spread operator. In a call,
...scoresexpands the array into its elements as separate arguments.Math.max(scores)without the dots receives one array argument and returnsNaN. The compiler reports thatnumber[]is not assignable to a parameter of typenumber, but the JavaScript still runs and printsNaN. for...of.for (const s of scores)hands out each value in order, which is all the sum needs, since the positions don't matter. A loop without braces runs the one statement after it.+=.total += smeanstotal = total + s.- Types are erased. The
: numberannotations are checked by the compiler, then removed from the JavaScript.
Complexity
Time: O(n). Math.max and Math.min each look at every score once, and the loop visits every score once. Three passes over n scores is still linear.
Space: O(1) extra for the program's own variables: highest, lowest, total and average. The spread calls pass the n values as arguments while they run, which is temporary.
Edge cases and common mistakes
- Rounding. For the starting scores
total / scores.lengthis 79.125 and the printed average is 79. WithoutMath.floorthe line would beAverage: 79.125. - One score. With
[70]all three lines show 70. - Two close scores. With
[80, 81]the output is highest 81, lowest 80 and average 80, since 80.5 rounds down. - An empty array.
Math.max(...[])is-InfinityandMath.min(...[])isInfinity. The average isMath.floor(0 / 0), which isNaN. The lesson's data always has scores, so nothing guards against this. - A very long array. Spreading hundreds of thousands of values into a call can overflow the call stack. An array of 200,000 numbers made
Math.max(...big)fail with "Maximum call stack size exceeded". For arrays that long, track the maximum in a loop. - Numbers stored as text. If the array held the strings
"92"and"78", the loop would build text instead of adding:totalwould be"09278". Thenumber[]annotation prevents that for ordinary code, but annotations don't convert anything at run time. - Dividing by a typed-in count. Writing
/ 8works for the starting array and breaks for any other length. Usescores.length.
Testing
- The starting scores print
Highest: 92,Lowest: 58andAverage: 79. [70]printsHighest: 70,Lowest: 70andAverage: 70.[80, 81]printsHighest: 81,Lowest: 80andAverage: 80.
