Problem overview
The data is three parallel arrays, names, productivities and salaries, where index i describes one employee. This version awards bonuses to the top k most productive employees, where k is a variable: k = 3 in the starter code, but the program must keep working for 1, 2, 5, 7 or any other value. Sorting is still off the table. The program repeats the search for the best employee k times and remembers who has already won, so nobody wins twice.
Each bonus is 15% of the salary, rounded down, and each winner gets a line name: $bonus, best first. If two employees are equally productive, the one listed first wins. For the starter data the output is:
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
If k is larger than the number of employees, everybody wins once and the extra rounds print nothing.
Approach: one search per round, with a "taken" flag
The previous version found the best and the second best with two hand-written loops. That doesn't scale to a variable k, so this version writes the search once and wraps it in a loop that runs k times.
Each round needs to ignore the people who already won. A Bool array named taken, with one slot per employee, records this: taken[i] is true once employee i has won. A round considers only the employees whose flag is still false, and when it picks a winner it flips that flag so later rounds skip them.
Inside a round, bestIndex starts at -1, meaning "nobody chosen yet". An employee becomes the round's best when they haven't won and either nobody is chosen yet or their productivity is strictly higher than the current best's. Strictly higher is what makes the first listed employee win a tie.
The rounds on the starter data
| Round | bestIndex | Winner | taken after the round |
|---|---|---|---|
| 0 | 3 | Alice Chen (150) | [false, false, false, true, false] |
| 1 | 1 | Mary Jane (133) | [false, true, false, true, false] |
| 2 | 4 | Carlos Diaz (120) | [false, true, false, true, true] |
Round 1 skips index 3 because it is taken, so Mary Jane (133) beats everybody who is left. Round 2 skips indices 1 and 3, and Carlos Diaz (120) beats Bob Smith (97) and John Doe (83).
Step by step
- Create
takenwithArray(repeating: false, count: names.count). It is avarbecause the flags change. Nobody has won yet, so every slot isfalse. - Write the rounds loop,
for rank in 0..<k. The counter only counts rounds; it is not used inside the loop. - Start each round with
var bestIndex = -1. It is created inside the loop so every round begins with nobody chosen. - Write the inner loop over
0..<names.count. Every round looks at all employees again. - Test each employee. They must not have won (
!taken[i]), and eitherbestIndex == -1or their productivity is strictly greater than that ofbestIndex. If so,bestIndex = i. - Check that someone was found with
bestIndex != -1. Whenkis larger than the number of employees, the last rounds find nobody, and using-1as an index would crash. - Mark the winner by setting
taken[bestIndex]totruestraight away, because the next round reads it. - Compute the bonus as
salaries[bestIndex] * 15 / 100. Integer division rounds the result down. - Print the winner as the name,
": $"and the bonus converted withString(...).
The solution in Swift
let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
let productivities = [83, 133, 97, 150, 120]
let salaries = [135000, 335000, 210000, 250000, 180000]
let k = 3
var taken = Array(repeating: false, count: names.count)
for rank in 0..<k {
var bestIndex = -1
for i in 0..<names.count {
if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
bestIndex = i
}
}
if bestIndex != -1 {
taken[bestIndex] = true
let bonus = salaries[bestIndex] * 15 / 100
print(names[bestIndex] + ": $" + String(bonus))
}
}
Swift specifics worth knowing:
Array(repeating:count:)builds an array of that many copies of a value. Arrays are value types, sotaken[bestIndex] = truechangestakenin place and needs thevar.String(bonus)is needed for+. Swift doesn't join aStringand anIntwith+. Writing"Alice" + ": $" + bonusis a compile error:binary operator '+' cannot be applied to operands of type 'String' and 'Int'. String interpolation,"\(names[bestIndex]): $\(bonus)", is the other common way.- The condition's grouping. The parentheses make the "nobody yet or higher" test one unit that is combined with
!taken[i].&&binds tighter than||, so without them the meaning would change. - Short-circuiting. When
bestIndex == -1is true, Swift doesn't evaluateproductivities[bestIndex], so the-1is never used as an index in that test. - The unused counter. Because
rankis never read, the compiler warns that the value was never used and suggests_. It is a warning, not an error, and the program runs. 0..<kis empty whenkis 0. The loop body never runs and nothing is printed. A negativekwould crash, because a range can't end before it starts.
Edge cases and common mistakes
klarger than the number of employees. Withk = 7and five employees, the output is five lines, one per employee, from Alice Chen down to John Doe. Rounds 5 and 6 find nobody, so thebestIndex != -1check keeps them silent.- Ties. With productivities
[10, 20, 20]andk = 2, the second and third employees are tied. The one listed first wins round 0 and the other wins round 1. Using>=instead of>would reverse that. - Forgetting to mark the winner. If
takenis never updated, every round finds the same employee and prints the same linektimes. - Creating
bestIndexoutside the rounds loop. The value from the previous round would stay, and the new round would start with a champion that has already won. - Using
bestIndexwithout the check. That works whilekis small and crashes whenkis larger than the number of employees.
Testing
These outputs come from the solution with other values of k on the starter data.
k = 1printsAlice Chen: $37500.k = 2printsAlice Chen: $37500andMary Jane: $50250.k = 5andk = 7both print five lines: Alice Chen $37500, Mary Jane $50250, Carlos Diaz $27000, Bob Smith $31500 and John Doe $20250.k = 0prints nothing.
Change k in the editor above and compare with these lines.
