Go: Rank the students

Sorting a slice of structs is a task you will meet again and again.

What to build

A program that ranks students by their score.

Requirements

  • Read n, then n lines name score.
  • Print one line per student in rank order: RANK. NAME (SCORE). The highest score comes first; students with the same score are ordered by name. Ranks are 1, 2, 3 and so on in the printed order.

Input

Line 1: n. Then n lines name score.

Output

n lines.

Constraints

1 ≤ n ≤ 50; scores are between 0 and 100; names are single words.

Example

Input:

4
Ada 90
Bob 75
Cy 90
Di 60

Output:

1. Ada (90)
2. Cy (90)
3. Bob (75)
4. Di (60)

Why it works

sort.Slice takes a function that says whether item i comes before item j. Comparing the score first and the name second gives a complete, fixed order.

Examples

Example 1 · Input
4
Ada 90
Bob 75
Cy 90
Di 60
Expected output
1. Ada (90)
2. Cy (90)
3. Bob (75)
4. Di (60)
Example 2 · Input
2
Zed 50
Amy 50
Expected output
1. Amy (50)
2. Zed (50)

Hints

Hint 1

Define type Student struct { Name string; Score int } and read them into a slice.

Hint 2

Use sort.Slice: higher score first, and the name in alphabetical order when scores are equal.

Solution

Show one correct solution (try it yourself first)
package main

import (
	"fmt"
	"sort"
)

type Student struct {
	Name  string
	Score int
}

func main() {
	var n int
	fmt.Scan(&n)
	students := []Student{}
	for i := 0; i < n; i++ {
		var s Student
		fmt.Scan(&s.Name, &s.Score)
		students = append(students, s)
	}
	sort.Slice(students, func(i, j int) bool {
		if students[i].Score != students[j].Score {
			return students[i].Score > students[j].Score
		}
		return students[i].Name < students[j].Name
	})
	for i, s := range students {
		fmt.Printf("%d. %s (%d)\n", i+1, s.Name, s.Score)
	}
}

▶ Open this solution in the compiler

Lesson: Structs →