TypeScript: Rank players with tuples

Use tuples to keep names and scores together, then print a ranking.

What to build

A program that ranks players by score.

Requirements

  • Store each player as a tuple [string, number].
  • Sort by score from highest to lowest; players with the same score are in alphabetical order of name.
  • Print R. NAME (SCORE) for each, where R is the position counting from 1.

Input

Line 1: n. Then n lines, each a name (one word) and a whole-number score.

Output

n lines.

Constraints

1 ≤ n ≤ 100; names are distinct.

Example

Input:

3
Rina 72
Arif 88
Zoya 80

Output:

1. Arif (88)
2. Zoya (80)
3. Rina (72)

Why it works

A tuple type keeps the two parts in a known order, so pair[0] is always the name and pair[1] always the score, and a sort comparison that falls back to the name gives every tie a fixed order.

Examples

Example 1 · Input
3
Rina 72
Arif 88
Zoya 80
Expected output
1. Arif (88)
2. Zoya (80)
3. Rina (72)
Example 2 · Input
4
dan 50
Cara 50
bob 70
Ali 50
Expected output
1. bob (70)
2. Ali (50)
3. Cara (50)
4. dan (50)

Hints

Hint 1

Keep each player as a tuple [string, number] in an array of type [string, number][].

Hint 2

Sort with a comparison that looks at the score first and the name second; localeCompare compares names.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
const n = Number(read());
const players: [string, number][] = [];
for (let i = 0; i < n; i++) {
  const [name, score] = read().split(" ");
  players.push([name, Number(score)]);
}
players.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
players.forEach((p, i) => console.log(i + 1 + ". " + p[0] + " (" + p[1] + ")"));

Lesson: Basic types: primitives, arrays, tuples and unknown →