Challenge: Sports Day Results
Completed
Read athletes with a name and a time in seconds. Rank them: fastest time first; if two times are equal, by name A–Z. Print each as <rank>. <name> <time>. Use a class and a Comparator.
Input
Line 1: n. Then n lines: name time.
Output
The ranked list.
Example
Input
4 Riya 14 Om 12 Anu 14 Ved 15
Output
1. Om 12 2. Anu 14 3. Riya 14 4. Ved 15
Editor
Java
Hints
Make a small class Athlete with name and time.
In the Comparator, compare times first; only if they're equal, compare names.
Solution explanation
Collections.sort is a stable O(n log n) sort; your Comparator just decides the order.
Show solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
class Athlete {
String name;
int time;
Athlete(String name, int time) {
this.name = name;
this.time = time;
}
}
class ByTimeThenName implements Comparator<Athlete> {
public int compare(Athlete a, Athlete b) {
if (a.time != b.time) return Integer.compare(a.time, b.time);
return a.name.compareTo(b.name);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<Athlete> list = new ArrayList<Athlete>();
for (int i = 0; i < n; i++) list.add(new Athlete(sc.next(), sc.nextInt()));
Collections.sort(list, new ByTimeThenName());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
Athlete a = list.get(i);
sb.append(i + 1).append(". ").append(a.name).append(' ').append(a.time).append('\n');
}
System.out.print(sb);
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module