Sort records by two rules: a score from high to low, and a name from A to Z when scores are equal.
What to build
A program that prints a ranking.
Requirements
- Read n, then n lines with a name and a score. The same name does not appear twice.
- Print the players sorted by score from high to low, and by name (A to Z) when scores are equal, as
1. name score,2. name scoreand so on.
Input
Line 1: n. Then n lines name score.
Output
n lines.
Constraints
1 ≤ n ≤ 50; names are single words; scores are integers from 0 to 1000.
Example
Input:
3
Ada 90
Bo 75
Cy 90
Output:
1. Ada 90
2. Cy 90
3. Bo 75
Why it works
The spaceship operator gives a number for the first rule, and the short ?: moves on to the second rule only when the first is a tie.
Examples
Example 1 · Input
3 Ada 90 Bo 75 Cy 90
Expected output
1. Ada 90 2. Cy 90 3. Bo 75
Example 2 · Input
2 Zed 10 Amy 10
Expected output
1. Amy 10 2. Zed 10
Hints
Hint 1
Keep the players in an array of records, or in an associative array name => score.
Hint 2
usort with $b["score"] <=> $a["score"] ?: strcmp($a["name"], $b["name"]) sorts by score first and name second.
Solution
Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
$players = [];
for ($i = 0; $i < $n; $i++) {
[$name, $score] = explode(" ", trim(fgets(STDIN)));
$players[] = ["name" => $name, "score" => (int) $score];
}
usort($players, fn($a, $b) => $b["score"] <=> $a["score"] ?: strcmp($a["name"], $b["name"]));
foreach ($players as $i => $p) {
echo $i + 1, ". ", $p["name"], " ", $p["score"], "\n";
}