Problem overview
Version 3 found the single best brand. Version 4 lists the top k brands by rating, best first. The brands and ratings are parallel slices, so brands[i] has the rating ratings[i]:
brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
k := 3
Each output line is rank. Brand (rating), starting at rank 1. When two brands have the same rating, the one listed first comes first. The value of k is never larger than the number of brands. For the starting data the output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
Approach: run the search k times and mark each winner
The previous version's search keeps the position of the best brand so far and replaces it only on a strictly higher rating. Running it once gives rank 1. To get rank 2, the same search must ignore the brand that already won. So the program keeps one bool flag per brand, used[i], which says whether brand i already has a rank. Each round searches only the brands that are not used yet, and then marks the winner.
The search starts each round with bestIndex equal to -1, meaning no brand found yet. It can't start at 0 the way version 3 did, since brand 0 may already be used. A brand is accepted when it is not used and either nothing has been found or its rating is strictly higher than the current best's. Strictness keeps the earlier brand on a tie.
The rounds on the starting data go like this:
- Round 1: TechPro (4) is found first, MegaCorp's 5 beats it, and NeoByte's 5 doesn't beat MegaCorp's, so MegaCorp wins.
- Round 2: MegaCorp is skipped. TechPro (4) is found first, then NeoByte (5) beats it, and nothing else does. NeoByte wins.
- Round 3: both 5s are used. TechPro (4) is found first, Zenith's 4 doesn't beat it, so TechPro wins.
This is a loop inside a loop: the outer loop counts ranks and the inner loop searches. For n brands the work is about k * n steps.
Step by step
- Create
used.make([]bool, len(ratings))gives one slot per brand, allfalse. - Create
lines, an empty[]string. Each round adds one finished line to it. - Write the rounds loop.
for rank := 1; rank <= k; rank++ {counts from 1 up to and includingk, so the counter is also the number printed in front of the brand. Close the brace right away. - Set
bestIndex := -1inside it, so each round starts the search over. - Write the inner loop.
for i := range ratings {visits each position of the ratings. - Skip used brands with
if !used[i] {. - Accept a better brand with
if bestIndex == -1 || ratings[i] > ratings[bestIndex] {, strictly greater. - Remember it:
bestIndex = i. - Mark the winner after the inner loop with
used[bestIndex] = true, so the next round skips it. - Add the line to
lineswithappend: the rank,". ", the brand name, and the rating in parentheses. The numbers go throughstrconv.Itoato be joined to the strings. - Print after the loop, joining the lines with a newline between them.
The solution in Go
brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
k := 3
used := make([]bool, len(ratings))
lines := []string{}
for rank := 1; rank <= k; rank++ {
bestIndex := -1
for i := range ratings {
if !used[i] {
if bestIndex == -1 || ratings[i] > ratings[bestIndex] {
bestIndex = i
}
}
}
used[bestIndex] = true
lines = append(lines, strconv.Itoa(rank) + ". " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")
}
fmt.Println(strings.Join(lines, "\n"))
The code uses the fmt, strconv and strings packages. The Go details worth knowing:
rangeover a slice.for i := range ratingswith one variable gives the indexes 0 tolen(ratings) - 1. It does the same as the counting loop without the bounds to write.makeand zero values. The slots of amake([]bool, n)slice are allfalse.appendreturns the slice. You must assign it back,lines = append(lines, x), because the result can be a new slice if the old one had no room.- The empty slice.
[]string{}is a slice of length 0 that is ready forappend. strings.Join. It glues the elements of a slice with a separator between each two and none at the end. Joined with"\n", the lines print one per line, andfmt.Printlnadds the final line break.- Short-circuit
||. WhenbestIndex == -1is true, the right side isn't evaluated, soratings[bestIndex]never reads index -1.
Complexity
Time is O(k * n): each of the k rounds scans all n brands once. Space is O(n + k), for the used flags and the k output lines. Sorting the brands by rating would cost O(n log n), which can be faster when k is large, but the repeated search is simple and needs no ordering of the data.
Edge cases and common mistakes
- Ties. With
>=instead of>, the later brand replaces the earlier one on a tie, and NeoByte would come before MegaCorp. When all five ratings are 3 andk = 3, the correct output is TechPro, MegaCorp and Quantum, in listed order. - Forgetting to mark the winner. Without
used[bestIndex] = true, every round finds MegaCorp. - Starting
bestIndexat 0. If brand 0 is used already, the search starts from a brand that must be skipped. klarger than the number of brands. The lesson promises that it won't happen. If it did, withk = 6and five brands, the sixth round would find nothing,bestIndexwould stay -1 andused[bestIndex]would panic withindex out of range [-1].kof 0. The loop doesn't run,linesis empty andfmt.Printlnprints an empty line.- Rank starting at 0. The loop must start at 1 so that the first line is
1. MegaCorp (5). - Joining inside the loop. Call
strings.Joinand print once, after the loop, or the earlier lines would be printed again in every round.
Testing
- The starting data with
k = 1prints1. MegaCorp (5). k = 3prints MegaCorp (5), NeoByte (5) and TechPro (4).k = 5adds4. Zenith (4)and5. Quantum (3)after those three lines.- Ratings
{3, 3, 3, 3, 3}withk = 3print TechPro, MegaCorp and Quantum, each with rating 3.
