Problem overview
Version 3 of the Top K Brands project works with any number of brands. They are stored in two parallel slices: brands[i] is a brand and ratings[i] is its rating. The starter data is:
brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
The program prints the highest-rated brand as 1. Brand (rating). Two brands share the top rating of 5, MegaCorp at position 1 and NeoByte at position 3, and the one listed first wins:
1. MegaCorp (5)
Approach: remember the position of the best so far
For a list, a loop works: keep the best brand found so far, and compare each new brand with it. The lesson keeps the position of the best brand in bestIndex, not its rating, because one position gives access to both the name and the rating through the two slices.
The variable starts at 0, since the first brand is the best of the brands seen so far. The loop then looks at positions 1, 2, 3 and so on. A brand replaces the current best only when its rating is strictly higher, so on a tie the earlier brand keeps the lead. That is how MegaCorp stays ahead of NeoByte.
Walking through the data: bestIndex starts at 0 (rating 4). Position 1 has 5 > 4, so bestIndex becomes 1. Position 2 has 3, no change. Position 3 has 5, which is not greater than 5, no change. Position 4 has 4, no change. The loop ends with bestIndex equal to 1.
Step by step
- Create
bestIndexand set it to 0. - Write the loop with
for i := 1; i < len(ratings); i++ {. It starts at 1 because position 0 is already the best so far. Close the brace at once so the next steps go inside. - Compare inside the loop:
if ratings[i] > ratings[bestIndex] {. Strictly greater. - Update inside the
if:bestIndex = i. - Print after the loop, reading
brands[bestIndex]andratings[bestIndex]. The rating goes throughstrconv.Itoaso that+can join it to the strings.
The solution in Go
brands := []string{"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"}
ratings := []int{4, 5, 3, 5, 4}
bestIndex := 0
for i := 1; i < len(ratings); i++ {
if ratings[i] > ratings[bestIndex] {
bestIndex = i
}
}
fmt.Println("1. " + brands[bestIndex] + " (" + strconv.Itoa(ratings[bestIndex]) + ")")
The code uses the fmt and strconv packages.
The details worth knowing
- Go has one loop keyword.
for init; condition; post { }is the classic counting loop. There is nowhile, and no parentheses around the three parts. lengives the length.len(ratings)is 5, and valid positions are 0 to 4. The conditioni < len(ratings)stops after position 4.- Indexing out of range panics. Reading
ratings[5]stops the program withindex out of rangeat run time. - Slices of the same length. The code assumes
brandsandratingshave the same length. Nothing in Go checks that for you.
Complexity
Time is O(n): the loop visits each of the other n - 1 positions once and does constant work per position. Extra space is O(1), because only bestIndex and i are added.
Edge cases and common mistakes
- Ties. With
>=in the comparison,bestIndexwould move to NeoByte at position 3 and the output would be1. NeoByte (5). The lesson's tests expect the first brand with the top rating. - An empty slice. With no brands,
ratings[bestIndex]reads position 0 of an empty slice and panics withindex out of range [0] with length 0. The lesson's data always has brands. - Storing the rating instead of the position. Then the brand's name cannot be found again without a second search.
- Looping to
len(ratings)inclusive.i <= len(ratings)reads one position too far and panics. - Starting the loop at 0. It still gives the right answer, since an element is never strictly greater than itself, but it makes one useless comparison.
Testing
- Ratings
{4, 5, 3, 5, 4}give MegaCorp (5). - Ratings
{5, 4, 3, 2, 1}give TechPro (5), where the best is already first. - Ratings
{1, 2, 3, 4, 5}give Zenith (5), the last position. - Ratings
{3, 3, 3, 3, 3}give TechPro (3), the first.
