Problem overview
Version 5 hands out two bonuses: one to the most productive employee and one to the second most productive. The data is the same three vectors as before, names, productivities and salaries, where index i in each describes one employee. Each bonus is 15% of the salary, rounded down. When two employees have the same productivity, the one listed first ranks higher.
For the example data, the scores are 83, 133, 97, 150 and 120. Alice Chen (150) is first and Mary Jane (133) is second. The program prints each name with its bonus, best first:
Alice Chen: $37500
Mary Jane: $50250
Note that second place receives a larger bonus here, because the bonus depends on the salary and not on the rank.
Approach: two passes, no sorting
Sorting the employees would work, but the three vectors would have to be reordered together. This lesson avoids that with two loops over the indexes:
- The first loop is the one from the previous version. It finds the index of the best employee.
- The second loop finds the best among all the other employees: it considers every index except the winner's.
The second loop needs a way to say "nobody chosen yet". An employee at index 0 can't serve as the starting champion, because index 0 might be the overall winner and must be skipped. So secondIndex starts at names.len(), one past the last valid index. Rust indexes are unsigned, so a negative marker like -1 isn't available, and the length works as a value that no real employee has.
An employee becomes the second best when two things are true. They are not the winner, and either nobody is chosen yet or their productivity is strictly greater than that of the current second. The strict comparison again keeps the earlier of two tied employees.
Step by step
- Create
bestIndexwithlet mut, starting at 0. - Loop from 1 up to the length, comparing each employee's productivity with the current best's.
- Update on a strictly higher score so ties go to the earlier employee.
- Create
secondIndexwithlet mutand start it atnames.len(), meaning nobody yet. - Start a second loop from 0. This pass starts at the first employee because the winner can be anywhere, and the loop skips them by index instead.
- Write the condition. The index must differ from
bestIndex, and eithersecondIndexstill equalsnames.len()orproductivities[i]beatsproductivities[secondIndex]. When it holds, setsecondIndextoi. - Compute
bestBonusfrom the best employee's salary. - Compute
secondBonusthe same way fromsecondIndex. - Print the best employee as the name, a colon, a dollar sign and the bonus.
- Print the second best in the same form on the next line.
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 mut bestIndex = 0;
for i in 1..names.len() {
if productivities[i] > productivities[bestIndex] {
bestIndex = i;
}
}
let mut secondIndex = names.len();
for i in 0..names.len() {
if i != bestIndex && (secondIndex == names.len() || productivities[i] > productivities[secondIndex]) {
secondIndex = i;
}
}
let bestBonus = salaries[bestIndex] * 15 / 100;
let secondBonus = salaries[secondIndex] * 15 / 100;
println!("{}: ${}", names[bestIndex], bestBonus);
println!("{}: ${}", names[secondIndex], secondBonus);
Details specific to Rust:
- Short-circuit order matters. In
secondIndex == names.len() || productivities[i] > productivities[secondIndex], the right side runs only when the left is false. WhilesecondIndexis stillnames.len(), the left side is true, soproductivities[secondIndex]is never evaluated. Reading that index would panic, because it is one past the end. - Parentheses group the
||.&&binds tighter than||, so without the parentheses the test would mean something different: the winner could be accepted by the second part. usizefor positions.names.len()returns ausize, sosecondIndexandbestIndexhave that type, and comparingi != bestIndexis a comparison of twousizevalues.- Style warnings. Names like
bestIndexandsecondBonustriggernon_snake_casewarnings, since Rust style prefersbest_indexandsecond_bonus. They are warnings only.
Complexity
Time: O(n). Two loops each visit the employees once. Space: O(1) extra, since only two indexes and two bonuses are stored. Sorting would cost O(n log n) and reorder the data, so two passes are cheaper here.
Edge cases and common mistakes
- Starting
secondIndexat 0. When the winner is employee 0, the second place would start as the winner. No other employee has a strictly higher productivity, so nothing replaces it and the same person is printed twice. Usingnames.len()as "nobody yet" avoids this. - Forgetting to skip the winner. Without
i != bestIndex, the second loop finds the same employee again and prints them twice. - Ties. For productivities 100, 100 and 100, the best is index 0 and the second is index 1. For 90, 100 and 100, the best is index 1 and the second is index 2.
- Winner first or last. For 200, 150 and 100 the second best is index 1. For two employees with productivities 10 and 20, the best is index 1 and the second is index 0.
- Fewer than two employees. With one employee, nobody can be second:
secondIndexstays atnames.len(), andsalaries[secondIndex]panics withindex out of bounds: the len is 1 but the index is 1. The lesson's data has five employees.
Testing
- The lesson's data prints
Alice Chen: $37500andMary Jane: $50250. - Names A, B, C with productivities 200, 150, 100 and salaries 1000, 2000, 3000 print
A: $150andB: $300. - With productivities 90, 100, 100 and the same names and salaries the output is
B: $300andC: $450. - With productivities 100, 100, 100 the output is
A: $150andB: $300. - Names A, B with productivities 10, 20 and salaries 1000, 2000 print
B: $300andA: $150.
