I'm trying to make a task. I need to take applicant first name, second name and GPA, then output only N applicants. (For example, i have 5 applicants, but only N (3) can pass through) To do this task, I decided to use a struct with ?slice of struct?. Struct looks like this:
type Applicant struct {
firstName string
secondName string
GPA float64
}
I created a slice and initialized it:
applicants := []Applicant{}
...
fmt.Scan(&firstName, &lastName, &GPA)
applicants = append(applicants, Applicant{firstName, lastName,
GPA})
Now my task is to output only names and only 3 of 5 applicants with highest GPA (I already sorted the slice from the best GPA to the worst). I tried to do output applicants slice like this, but got error:
for _, applicant := range M {
fmt.Println(applicant.secondName " "
applicant.secondName)
}
Can you help me with slice name output?
CodePudding user response:
To get the first 3 with highest GPA you first sort the slice (what you alread did) and then just create a subslice:
func GetTopThree(applicants []Applicant) []Applicant {
sort.Slice(applicants, func(i, j int) bool {
return applicants[i].GPA > applicants[j].GPA
})
return applicants[:3]
}
To just get the names you can create a new slice
func GetTopThreeNames(applicants []Applicant) []string {
var topThree []string
for i := 0; i < int(math.Min(3, float64(len(applicants)))); i {
topThree = append(topThree, applicants[i].firstName)
}
return topThree
}
CodePudding user response:
If you want to map the first names and last names separately, this could be an approach:
func TopThreeNames(applicants []Applicant) [][2]string {
top := applicants[:int(math.Min(3, float64(len(applicants))))]
var names [][2]string
for _, a := range top {
names = append(names, [2]string{a.firstName, a.secondName})
}
return names
}
The function maps each Applicant
element to an array of length two, whereby the first element is equal to its first name and the second element to its second name.
For instance (unsafe since the length of the slice could be empty):
names := TopThreeNames(applicants)
first := names[0]
fmt.Printf("First name: %s and last name: %s\n", first[0], first[1])
CodePudding user response:
If your task really is just to print out the names then this is one possible way
for i := 0; i < 3 && i < len(applicants); i {
fmt.Printf("%s %s\n", applicants[i].firstName, applicants[i].secondName)
}
Note that the list must be sorted first like is is shown in other posts.