TypeScript: A grade histogram with Record

Count grades in a Record keyed by a literal union, so no grade can be forgotten, and draw a histogram.

What to build

A program that turns scores into grades and prints a histogram.

Requirements

  • Declare type Grade = "A" | "B" | "C" | "D" | "F" and count into a Record<Grade, number>.
  • Grades: A 90 and above, B 80 to 89, C 70 to 79, D 60 to 69, F below 60.
  • Print G | STARS (K) for each grade from A to F, one star per student, even when K is 0.
  • Then print most common: G (the earliest of A to F among those with the highest count).

Input

Line 1: n. Line 2: n scores separated by spaces.

Output

Six lines.

Constraints

1 ≤ n ≤ 100; 0 ≤ score ≤ 100.

Example

Input:

6
95 82 71 88 40 99

Output:

A | ** (2)
B | ** (2)
C | * (1)
D |  (0)
F | * (1)
most common: A

Why it works

Because the keys of the Record are the literal union, the starting object must contain every grade, so a grade with no students still prints a line, and adding a grade to the union would make the compiler demand its count.

Examples

Example 1 · Input
6
95 82 71 88 40 99
Expected output
A | ** (2)
B | ** (2)
C | * (1)
D |  (0)
F | * (1)
most common: A
Example 2 · Input
3
10 20 65
Expected output
A |  (0)
B |  (0)
C |  (0)
D | * (1)
F | ** (2)
most common: F

Hints

Hint 1

type Grade = "A" | "B" | "C" | "D" | "F", and const counts: Record<Grade, number> must list all five.

Hint 2

"*".repeat(k) draws a bar of k stars.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

type Grade = "A" | "B" | "C" | "D" | "F";
const GRADES: Grade[] = ["A", "B", "C", "D", "F"];

function gradeOf(score: number): Grade {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

const n = Number(read());
const scores = read().split(" ").map(Number);
const counts: Record<Grade, number> = { A: 0, B: 0, C: 0, D: 0, F: 0 };
for (const s of scores) counts[gradeOf(s)]++;
let best: Grade = "A";
for (const g of GRADES) {
  console.log(g + " | " + "*".repeat(counts[g]) + " (" + counts[g] + ")");
  if (counts[g] > counts[best]) best = g;
}
console.log("most common: " + best);

Lesson: Utility types →