Problem overview
Two parallel arrays describe five brands: brands holds the names and ratings holds their ratings, so position i in both refers to the same brand. A variable k says how many brands to show. The program prints the top k brands, best first, one per line, in the form rank. Brand (rating), starting at rank 1.
When two brands have the same rating, the one listed first ranks higher. For the starter data, where k = 3, MegaCorp and NeoByte both have a 5 and MegaCorp is listed first, so the output is:
1. MegaCorp (5)
2. NeoByte (5)
3. TechPro (4)
In this version k is never larger than the number of brands.
Approach: find the best, mark it taken, search again
The previous version found the single best brand with one scan. To get the top k, the lesson repeats that scan k times. The only new problem is that every round after the first would find the same brand again, unless the earlier winners are ignored.
A Bool array named used solves it. It has one flag per brand, all false at the start. A round looks only at brands whose flag is still false, picks the best of them, and sets that brand's flag to true. The next round then skips it, so the second-best brand can win, and so on.
Inside a round the scan keeps a bestIndex that starts at -1, meaning "none found yet". A brand replaces the current best only if nothing is chosen yet or its rating is strictly higher. Strictly higher is what lets the earlier brand keep a tie.
The cost is k scans of n brands, so the work grows with k * n. That is fine for small lists, and it needs no sorting.
The rounds on the starter data
| Round (rank) | bestIndex | Winner | used after the round |
|---|---|---|---|
| 1 | 1 | MegaCorp (5) | [false, true, false, false, false] |
| 2 | 3 | NeoByte (5) | [false, true, false, true, false] |
| 3 | 0 | TechPro (4) | [true, true, false, true, false] |
In round 1, MegaCorp at index 1 reaches a 5 first, and NeoByte's 5 at index 3 is not strictly higher, so MegaCorp keeps the spot. In round 2 MegaCorp is skipped, so NeoByte wins. In round 3 the two 5s are gone, and TechPro at index 0 reaches a 4 before Zenith, which ties it and doesn't replace it.
Step by step
- Create
usedwithArray(repeating: false, count: ratings.count), avarbecause the flags change. - Create
linesas an empty[String]. Each round adds one finished line to it. - Loop over the ranks with
for rank in 1...k. The counter does two jobs: it repeats the search once per winner and it is the number printed before the brand. - Start the round with
var bestIndex = -1. It is declared inside the loop, so every round restarts the search. - Loop over the positions of
ratingswithfor index in ratings.indices. Each round scans all brands from the start. - Skip the taken brands with
if !used[index]. - Test the candidate. Inside, check
bestIndex == -1 || ratings[index] > ratings[bestIndex]. - Remember it by setting
bestIndex = index. - After the scan, mark the winner with
used[bestIndex] = true. - Add the line to
lineswithappend, using string interpolation for the rank, the name and the rating. - Print once at the end with
lines.joined(separator: "\n").
The solution in Swift
let brands = ["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"]
let ratings = [4, 5, 3, 5, 4]
let k = 3
var used = Array(repeating: false, count: ratings.count)
var lines = [String]()
for rank in 1...k {
var bestIndex = -1
for index in ratings.indices {
if !used[index] {
if bestIndex == -1 || ratings[index] > ratings[bestIndex] {
bestIndex = index
}
}
}
used[bestIndex] = true
lines.append("\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]))")
}
print(lines.joined(separator: "\n"))
Swift specifics worth knowing:
1...kis a closed range. It includesk, sok = 3gives ranks 1, 2 and 3. The half-open1..<kwould stop one short. Ifkwere 0,1...0is invalid and the program crashes at run time.ratings.indicesis the range of valid positions,0..<5here.- Interpolation handles numbers.
"\(rank). \(brands[bestIndex]) (\(ratings[bestIndex]))"puts anIntand aStringin one line. NoString(...)conversion is needed, unlike with+. joined(separator:)glues the strings of an array with the separator between each pair, and none after the last. Oneprintthen shows every line, andprintadds the final newline.- Bounds are checked.
used[-1]would stop the program, so the code relies on every round finding a brand. That holds becauseknever exceeds the number of brands.
Edge cases and common mistakes
- Ties. With
ratings = [2, 2, 2]andk = 3, the brands come out in their listed order. Using>=instead of>would make the last tied brand win each round. k = 1. The loop runs once and the output is only the best brand:1. MegaCorp (5).kequal to the number of brands. Withk = 5every brand is printed, in order: MegaCorp (5), NeoByte (5), TechPro (4), Zenith (4), Quantum (3).- Not marking the winner. Without
used[bestIndex] = true, every round returns MegaCorp. - Declaring
bestIndexoutside the loop. The old winner would stay as the starting best, and a taken brand could appear again. klarger than the number of brands. This lesson promises it doesn't happen. If it did, the last rounds would leavebestIndexat-1andused[bestIndex]would crash.
Testing
These outputs come from running the solution on the starter arrays with other values of k.
k = 1prints1. MegaCorp (5).k = 2prints1. MegaCorp (5)and2. NeoByte (5).k = 5prints the five lines listed above, ending with5. Quantum (3).
Try it in the editor above, and set two ratings equal to check the tie rule.
