{ }codelper
recordslists of recordscustom sortingP0067

Score ranking

The first line gives the number of students n, and each of the next n lines gives "name korean english math" separated by single spaces.
Compute each student's total of the three subjects and print a ranking.
List students with a larger total first; when totals are equal, order by name in character-code order (ASCII: uppercase before lowercase; if one name is the start of another, the shorter comes first).
On each line print "rank name total".
The rank is 1 + (the number of students with a larger total), so students with equal totals share a rank and the next rank skips accordingly (e.g.
1, 1, 3).

Input
1 ≤ n ≤ 1000, 0 ≤ score ≤ 100 (integer).
Names are 1 to 10 English letters (upper or lower case) and are distinct
Output
n lines, each with rank, name and total separated by single spaces
Example 1 · stdin
5
mina 90 85 100
Jun 80 95 100
alex 70 60 50
seo 100 100 75
Bora 60 60 60
stdout
1 Jun 275
1 mina 275
1 seo 275
4 Bora 180
4 alex 180
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Each language bundles one student (name, total) differently: Python @dataclass (or a tuple), Java record Student(String name, int total), C# record Student(string Name, int Total), C and C++ struct, JS/TS an object { name, total } (TS describes its shape with an interface).
Craykon has no classes, so each student is one Dict() (s["name"], s["total"]) put in a list, and you pass a compare function's name as in students.Sort(ByTotal).
Three traps: (1) keeping a names list and a totals list side by side (parallel lists) and sorting only the totals breaks the pairs; sort the bundled records.
(2) In Python, sorting (total, name) with reverse=True also reverses the names (use key=lambda s: (-s.total, s.name)).
(3) Comparing names: JS localeCompare uses human dictionary order, so "amy" comes before "Bob", and C#'s default string comparison may follow culture rules too.
Character-code order is JS <, C# StringComparer.Ordinal, Java compareTo, C strcmp, C++ <.
The rank is not the position i + 1; change it to i + 1 only when the total differs from the previous student's.

Pythonmain.py · 23 lines
import sysfrom dataclasses import dataclass  @dataclassclass Student:    name: str    total: int  lines = sys.stdin.read().split("\n")n = int(lines[0])students = []for line in lines[1:n + 1]:    name, *scores = line.split()    students.append(Student(name, sum(map(int, scores)))) students.sort(key=lambda s: (-s.total, s.name))rank = 0for i, s in enumerate(students):    if i == 0 or s.total != students[i - 1].total:        rank = i + 1    print(rank, s.name, s.total)
JavaScriptmain.js · 16 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const n = Number(lines[0]);const students = [];for (let i = 1; i <= n; i++) {  const [name, ...scores] = lines[i].trim().split(" ");  students.push({ name, total: scores.reduce((sum, x) => sum + Number(x), 0) });}// 이름은 글자 코드 순(< 비교). localeCompare는 대소문자를 사람 사전처럼 섞는다students.sort((a, b) => b.total - a.total || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));const out = [];let rank = 0;students.forEach((s, i) => {  if (i === 0 || s.total !== students[i - 1].total) rank = i + 1;  out.push(`${rank} ${s.name} ${s.total}`);});console.log(out.join("\n"));
TypeScriptmain.ts · 22 lines
import { readFileSync } from "node:fs"; interface Student {  name: string;  total: number;} const lines: string[] = readFileSync(0, "utf8").split("\n");const n: number = Number(lines[0]);const students: Student[] = [];for (let i = 1; i <= n; i++) {  const [name, ...scores] = lines[i].trim().split(" ");  students.push({ name, total: scores.reduce((sum, x) => sum + Number(x), 0) });}students.sort((a, b) => b.total - a.total || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));const out: string[] = [];let rank = 0;students.forEach((s, i) => {  if (i === 0 || s.total !== students[i - 1].total) rank = i + 1;  out.push(`${rank} ${s.name} ${s.total}`);});console.log(out.join("\n"));
JavaMain.java · 31 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.Comparator;import java.util.List; public class Main {    record Student(String name, int total) {}     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int n = Integer.parseInt(in.readLine().trim());        List<Student> students = new ArrayList<>();        for (int i = 0; i < n; i++) {            String[] p = in.readLine().trim().split(" ");            int total = Integer.parseInt(p[1]) + Integer.parseInt(p[2]) + Integer.parseInt(p[3]);            students.add(new Student(p[0], total));        }        // String.compareTo는 글자 코드 순이다(대문자가 소문자보다 먼저)        students.sort(Comparator.comparingInt(Student::total).reversed().thenComparing(Student::name));        StringBuilder out = new StringBuilder();        int rank = 0;        for (int i = 0; i < n; i++) {            Student s = students.get(i);            if (i == 0 || s.total() != students.get(i - 1).total()) rank = i + 1;            out.append(rank).append(' ').append(s.name()).append(' ').append(s.total()).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 27 lines
using System;using System.Collections.Generic;using System.Linq; record Student(string Name, int Total); class Program{    static void Main()    {        int n = int.Parse(Console.ReadLine());        var students = new List<Student>();        for (int i = 0; i < n; i++)        {            string[] p = Console.ReadLine().Trim().Split(' ');            students.Add(new Student(p[0], p.Skip(1).Sum(int.Parse)));        }        // 기본 문자열 비교는 문화권 규칙을 따를 수 있어 글자 코드 순(Ordinal)을 밝혀 준다        var sorted = students.OrderByDescending(s => s.Total).ThenBy(s => s.Name, StringComparer.Ordinal).ToList();        int rank = 0;        for (int i = 0; i < sorted.Count; i++)        {            if (i == 0 || sorted[i].Total != sorted[i - 1].Total) rank = i + 1;            Console.WriteLine($"{rank} {sorted[i].Name} {sorted[i].Total}");        }    }}
C++main.cpp · 30 lines
#include <algorithm>#include <iostream>#include <string>#include <vector> struct Student {    std::string name;    int total;}; int main() {    int n;    std::cin >> n;    std::vector<Student> students;    for (int i = 0; i < n; i++) {        std::string name;        int k, e, m;        std::cin >> name >> k >> e >> m;        students.push_back({name, k + e + m});    }    std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {        if (a.total != b.total) return a.total > b.total;        return a.name < b.name;    });    int rank = 0;    for (int i = 0; i < n; i++) {        if (i == 0 || students[i].total != students[i - 1].total) rank = i + 1;        std::cout << rank << ' ' << students[i].name << ' ' << students[i].total << '\n';    }}
Cmain.c · 32 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> struct Student {    char name[11];    int total;}; static int by_total_then_name(const void *pa, const void *pb) {    const struct Student *a = pa, *b = pb;    if (a->total != b->total) return b->total - a->total;    return strcmp(a->name, b->name); /* 글자 코드 순 */} int main(void) {    static struct Student s[1000];    int n;    scanf("%d", &n);    for (int i = 0; i < n; i++) {        int k, e, m;        scanf("%10s %d %d %d", s[i].name, &k, &e, &m);        s[i].total = k + e + m;    }    qsort(s, n, sizeof s[0], by_total_then_name);    int rank = 0;    for (int i = 0; i < n; i++) {        if (i == 0 || s[i].total != s[i - 1].total) rank = i + 1;        printf("%d %s %d\n", rank, s[i].name, s[i].total);    }    return 0;}
Craykonmain.cray · 36 lines
// 크레이콘에는 클래스가 없어서 학생 한 명을 사전 하나(이름·합계)로 묶는다n = Console.ReadLine().ToNumber();students = [];for (i = 0; i < n; i++){    p = Console.ReadLine().Trim().Split();    s = Dict();    s["name"] = p[0];    s["total"] = p[1].ToNumber() + p[2].ToNumber() + p[3].ToNumber();    students.Add(s);}students.Sort(합계순);rank = 0;for (i = 0; i < n; i++){    s = students[i];    if (i == 0 || s["total"] != students[i - 1]["total"])    {        rank = i + 1;    }    Console.WriteLine(rank + " " + s["name"] + " " + s["total"]);} // 합계가 큰 것 먼저, 같으면 이름의 글자 코드 순합계순(앞, 뒤){    if (앞["total"] != 뒤["total"])    {        return 뒤["total"] - 앞["total"];    }    if (앞["name"] < 뒤["name"])    {        return -1;    }    return 1;}