Problem overview
A company gives bonuses to its k most productive employees. Three vectors describe the staff: names, productivities and salaries. Index i in all three refers to the same person. The starting data has five employees and k = 3.
The program prints one line per winner, best first, in the form name: $bonus. A bonus is 15% of the salary, rounded down by integer division. For the starting data:
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
Alice has the highest productivity, 150, and a salary of 250000, which gives 37500. Mary is next with 133, and Carlos third with 120. If two employees have the same productivity, the one listed first wins. If k is larger than the number of employees, everybody wins once and nothing extra is printed. The program must keep working when k changes.
Approach: repeat the search, remember the winners
Sorting is not allowed here. Instead, the program repeats a plain search for the best employee k times. A search by itself would find Alice every time, so it needs a way to skip people who already won. A vector of flags, taken, has one false for each employee, and a winner's flag is switched to true. Every later round ignores flagged employees, so round 2 finds the best among those who remain.
Each round needs a way to say "nobody found yet". Rust indexes are unsigned, so the usual -1 is unavailable. The program uses names.len() instead: it is one past the last valid index, so no real employee can have that value.
The test for a new best employee has two parts. The employee must not be taken, and either nobody has been chosen in this round yet, or this employee's productivity is strictly greater than the current best's. Strictly greater is what implements the tie rule: a later employee with equal productivity doesn't replace an earlier one.
After the search, the program checks that it found someone. When k is larger than the staff, the late rounds find nobody and must print nothing.
Step by step
- Create
takenwithvec![false; names.len()]: one flag per employee, all false because nobody has won yet. - Start the rounds with
for _rank in 0..k. The counter only counts rounds, and the leading underscore tells Rust it is never read. - Create
bestIndexinside the round with the valuenames.len(), meaning nobody is chosen. Creating it inside the loop resets it every round. - Open the inner loop over every position
iin0..names.len(). Each round looks at everybody again. - Test each employee. The
ifrequires!taken[i]and eitherbestIndex == names.len()or a strictly higher productivity thanbestIndex. When it holds,bestIndexbecomesi. - Check that someone was found after the inner loop:
bestIndex != names.len(). Otherwise the code below would index a vector with a value that is not an employee. - Mark the winner by setting
taken[bestIndex]totrue, immediately, because the next round reads it. - Compute
bonusas the winner's salary times 15 divided by 100. - Print the line with the name at
bestIndexand the bonus.
The solution in Rust
let names = vec!["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
let productivities = vec![83, 133, 97, 150, 120];
let salaries = vec![135000, 335000, 210000, 250000, 180000];
let k = 3;
let mut taken = vec![false; names.len()];
for _rank in 0..k {
let mut bestIndex = names.len();
for i in 0..names.len() {
if !taken[i] && (bestIndex == names.len() || productivities[i] > productivities[bestIndex]) {
bestIndex = i;
}
}
if bestIndex != names.len() {
taken[bestIndex] = true;
let bonus = salaries[bestIndex] * 15 / 100;
println!("{}: ${}", names[bestIndex], bonus);
}
}
Rust details worth knowing:
- Short-circuit evaluation.
||and&&stop as soon as the answer is known. WhenbestIndex == names.len()is true, the right side,productivities[bestIndex], is never evaluated. That matters, because evaluating it would index one past the end and panic. - Precedence.
&&binds tighter than||, so the parentheses are needed to make!taken[i]apply to both alternatives. $in the format string. The$before the second{}is an ordinary character inprintln!, so it prints as a dollar sign.- Naming style. Rust convention would call the variable
best_index, and the compiler warns about the camel-casebestIndex. It is a warning only, and the output is correct. - Integer arithmetic. The salaries are
i32values, sosalary * 15 / 100multiplies first and divides second. For a salary of 135000 it gives 20250, and for a salary of 999 it gives 149, with the fraction dropped.
Complexity
Time: O(k * n) for n employees, because each of the k rounds scans all n of them. With k equal to n this becomes O(n²), which is why sorting would be better for a large staff. Space: O(n) for the taken flags.
Edge cases and common mistakes
- Different values of
k. Withk = 1the output is only Alice. Withk = 2it is Alice and Mary. Withk = 0nothing is printed. klarger than the staff. Withk = 5the output is Alice Chen ($37500), Mary Jane ($50250), Carlos Diaz ($27000), Bob Smith ($31500) and John Doe ($20250). Withk = 7it is the same five lines: the last two rounds find nobody and print nothing.- Ties. For employees A, B and C with productivities 100, 100 and 90, and salaries 1000, 2000 and 3000,
k = 2givesA: $150and thenB: $300. A, listed first, wins the tie. With>=in the comparison, B would replace A. - Forgetting to mark the winner. If
taken[bestIndex]is never set, every round finds Alice again and prints herktimes. - Creating
bestIndexoutside the rounds. It would keep the previous winner, and later rounds would compare against someone already taken. - Skipping the "found" check. When
kexceeds the staff,names[bestIndex]withbestIndexequal to the length panics withindex out of bounds.
Testing
- The starting data with
k = 3prints Alice Chen $37500, Mary Jane $50250 and Carlos Diaz $27000. k = 1printsAlice Chen: $37500only.k = 5andk = 7print all five employees in order of productivity: Alice, Mary, Carlos, Bob, John.k = 0prints nothing.
