Problem overview
Many brands sell the same product. They are stored in two parallel arrays: ratings[i] is the rating of brands[i]. The program finds the highest-rated brand by scanning with a loop and prints it as 1. Brand (rating). If two brands share the top rating, the one listed first wins.
For the starter data, ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"] with ratings [4, 5, 3, 5, 4], the top rating is 5. MegaCorp (position 1) and NeoByte (position 3) both have it, and MegaCorp is listed first:
1. MegaCorp (5)
Version 2 chose between two brands with an if/else. A loop does the same job for any number of brands.
Approach: remember the position of the best so far
Keep a variable, bestIndex, holding the position of the best brand seen so far. Start it at 0: with nothing else to compare against, the first brand is the best so far. Then look at positions 1 to the end. Each time a rating is strictly higher than the one at bestIndex, move bestIndex to that position.
The program stores the position, not the rating itself, because one position reaches both arrays: brands[bestIndex] is the name and ratings[bestIndex] is its rating.
The scan on the starter data
| index | ratings[index] | bestIndex after the check |
|---|---|---|
| 1 | 5 | 1 |
| 2 | 3 | 1 |
| 3 | 5 | 1 |
| 4 | 4 | 1 |
At position 3, the rating 5 is equal to the best, not strictly greater, so bestIndex stays at 1. That is how the tie goes to MegaCorp.
Step by step
- Create
bestIndexas avarset to 0. It will change, and for now the first brand is the best. - Write the
forloop over1..<ratings.count. Position 0 is already the best so far, so the scan starts at 1. The loop variable is namedindexin the code. - Inside the loop, add an
ifthat tests whether this brand's rating is strictly greater than the rating atbestIndex. - Inside the
if, setbestIndexto the current position. - After the loop, print the winner with interpolation: the rank
1., the brand atbestIndex, a space and an opening parenthesis, the rating atbestIndex, then a closing parenthesis.
The solution in Swift
let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
let ratings = [4, 5, 3, 5, 4]
var bestIndex = 0
for index in 1..<ratings.count {
if ratings[index] > ratings[bestIndex] {
bestIndex = index
}
}
print("1. \(brands[bestIndex]) (\(ratings[bestIndex]))")
The Swift details worth knowing:
- Half-open range.
1..<ratings.countstarts at 1 and stops beforeratings.count. With five ratings the values are 1, 2, 3 and 4. The closed form1...ratings.countwould include 5, andratings[5]is out of bounds, so it crashes at run time. - Expressions inside interpolation.
\(brands[bestIndex])and\(ratings[bestIndex])hold whole subscript expressions. Any expression works inside the parentheses. - Arrays of one type.
brandsis a[String]andratingsis an[Int]. They are separate arrays that the program keeps in step by position, so they must have the same length. - Constants and variables. The arrays are
lets, since the loop only reads them, whilebestIndexis avar.
Complexity
Time: O(n). The loop visits each of the other n - 1 positions once and does a constant amount of work at each.
Space: O(1). The program stores one integer, bestIndex, no matter how many brands there are.
Edge cases and common mistakes
- Ties. The strict
>keeps the earlier brand. Changing it to>=makes the later brand replace it, and the starter data would then print1. NeoByte (5). - One brand. With only
["TechPro"]and[4], the range1..<1is empty, the loop body doesn't run, and the program prints1. TechPro (4). - No brands. With empty arrays, the range
1..<0is invalid andbrands[0]doesn't exist, so the program crashes. The lesson's data always has at least one brand. - Storing the rating instead of the position. You would know the top score but not which brand earned it.
- Arrays of different lengths. If
brandswere shorter thanratings, the final subscript could go out of bounds. The loop usesratings.count, so the two arrays must match.
Testing
- The starter data prints
1. MegaCorp (5). - Using
>=in the comparison, the same data prints1. NeoByte (5). - The single brand
["TechPro"]with ratings[4]prints1. TechPro (4).
