Problem overview
Now a whole team competes. The data sits in three vectors, names, productivities and salaries, and index i in each one describes the same employee. The program finds the employee with the highest productivity and prints their name and their bonus, 15% of the salary rounded down. If several employees share the top score, the one listed first wins.
In the example, the scores are 83, 133, 97, 150 and 120. The highest is 150, which belongs to Alice Chen at index 3. Her salary is 250000, so the bonus is 250000 * 15 / 100 = 37500:
Alice Chen
Bonus: $37500
Approach: remember the best index so far
The earlier versions compared a fixed number of employees with if and else if. That doesn't work for a list of any length, so the program uses a loop and one variable: the index of the best employee seen so far.
It starts by assuming employee 0 is the best. The loop then visits every other employee. Whenever one has a strictly higher productivity than the current best, the stored index moves to that employee. When the loop ends, the stored index points at the winner.
The program keeps an index and not the score because one index unlocks all three vectors. names[bestIndex] and salaries[bestIndex] then give the winner's name and salary without any extra variables.
The comparison is strict (>), which implements the tie rule. When a later employee ties the current best, the condition is false and the earlier one stays in front.
Step by step
- Create
bestIndexwithlet mutand the value 0. It needsmutbecause the loop will change it. - Loop over the remaining indexes. The range
1..names.len()starts at 1, since employee 0 is the starting champion, and stops beforenames.len(). For five employees the loop sees 1, 2, 3 and 4. - Compare inside the loop. If
productivities[i]is strictly greater thanproductivities[bestIndex], assignitobestIndex. - Compute the bonus after the loop from
salaries[bestIndex], multiplying by 15 and then dividing by 100. - Print the name
names[bestIndex]on its own line. - Print the bonus line as
Bonus: $followed by the amount.
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 bonus = salaries[bestIndex] * 15 / 100;
println!("{}", names[bestIndex]);
println!("Bonus: ${}", bonus);
Rust details worth knowing:
- Ranges are half-open.
1..names.len()includes 1 and excludes the length.1..=names.len()would include the length, which isn't a valid index, and the program would panic at that point. - Indexes are
usize.bestIndexstarts as the literal 0, and because it is used to index a vector, Rust infersusizefor it. The loop variableiis ausizeas well, sobestIndex = itype-checks. Ausizecan't hold a negative number. - Naming style. The names
bestIndexfollow the lesson's steps, but Rust's convention is snake case,best_index. The compiler prints anon_snake_casewarning forbestIndex. It is a style warning only, and the program still runs. vec!builds a vector. Its elements are the same type:&strfor names andi32by default for the numbers. Indexing a vector out of range panics instead of returning garbage.
Complexity
Time: O(n) for n employees. The loop visits each employee once and does a constant amount of work for each. Space: O(1) extra, because the program stores only one index and one bonus.
Edge cases and common mistakes
- Ties. With productivities 100, 100 and 90, the winner is the first employee. Using
>=in the comparison would move the index to the second. - The best employee is first. If employee 0 has the top score, the condition is never true and
bestIndexstays 0. - The best employee is last. The loop reaches the last index, so with scores 1, 2 and 3 the winner is index 2.
- One employee. The range
1..1is empty, the loop doesn't run, and employee 0 wins. That is correct. - No employees. The empty range
1..0doesn't panic either, butsalaries[bestIndex]then reads index 0 of an empty vector and the program panics withindex out of bounds: the len is 0 but the index is 0. The lesson's data always has employees. - Starting the loop at 0. It still gives the right answer, because comparing employee 0 with itself is never strictly greater, but it does one pointless comparison.
- Vectors of different lengths. The loop uses
names.len(). Ifproductivitieswere shorter, indexing it would panic.
Testing
- The lesson's data prints
Alice ChenandBonus: $37500. - Names A, B, C with productivities 100, 100, 90 and salaries 1000, 2000, 3000 print
AandBonus: $150. - Names A, B, C with productivities 1, 2, 3 and the same salaries print
CandBonus: $450. - A single employee A with salary 1000 prints
AandBonus: $150.
