Write one generic grouping function and use it for two different kinds of data.
What to build
A program that groups students by grade and words by their first letter.
Requirements
- Write
groupBy<T>(items: T[], keyOf: (item: T) => string): Map<string, T[]>; items keep their input order inside each group. - Grade: A for 80 and above, B for 65 to 79, C for 50 to 64, F below 50. Print
GRADE: NAME, NAMEfor each grade that has students, grades in alphabetical order. - Then group the words by first letter (lower case) and print
LETTER: WORD WORDfor each letter in alphabetical order.
Input
Line 1: n. Then n lines NAME SCORE. Then one line of words separated by spaces.
Output
The grade lines, then the letter lines.
Constraints
1 ≤ n ≤ 50; 0 ≤ score ≤ 100; 1 to 50 words, of letters only.
Example
Input:
4
Rina 91
Arif 64
Zoya 80
Omar 30
apple Banana avocado cherry blueberry
Output:
A: Rina, Zoya
C: Arif
F: Omar
a: apple avocado
b: Banana blueberry
c: cherry
Why it works
The function is written once and returns a Map of the caller's own type, so the grade groups hold students and the letter groups hold strings, each with full type checking.
Examples
Example 1 · Input
4 Rina 91 Arif 64 Zoya 80 Omar 30 apple Banana avocado cherry blueberry
Expected output
A: Rina, Zoya C: Arif F: Omar a: apple avocado b: Banana blueberry c: cherry
Example 2 · Input
2 X 65 Y 79 zebra
Expected output
B: X, Y z: zebra
Hints
Hint 1
groupBy<T>(items: T[], keyOf: (item: T) => string): Map<string, T[]> keeps groups in first-seen order.
Hint 2
Sort the keys when printing.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
interface Student {
name: string;
score: number;
}
function groupBy<T>(items: T[], keyOf: (item: T) => string): Map<string, T[]> {
const groups = new Map<string, T[]>();
for (const item of items) {
const key = keyOf(item);
const group = groups.get(key);
if (group) group.push(item);
else groups.set(key, [item]);
}
return groups;
}
function grade(score: number): string {
if (score >= 80) return "A";
if (score >= 65) return "B";
if (score >= 50) return "C";
return "F";
}
const n = Number(read());
const students: Student[] = [];
for (let i = 0; i < n; i++) {
const [name, score] = read().split(" ");
students.push({ name, score: Number(score) });
}
const words = read().split(" ");
const byGrade = groupBy(students, (s) => grade(s.score));
for (const key of [...byGrade.keys()].sort()) {
console.log(key + ": " + (byGrade.get(key) ?? []).map((s) => s.name).join(", "));
}
const byLetter = groupBy(words, (w) => w[0].toLowerCase());
for (const key of [...byLetter.keys()].sort()) {
console.log(key + ": " + (byLetter.get(key) ?? []).join(" "));
}