Start learning free

LESSON 189 OF 293 · LOOPING OVER ARRAY INDICES

Employee Of The Year V4 in Rust: Looping Over Vector Indices

Practice Read the full explanation

A whole team is competing. Use a for loop over the vectors to find the most productive employee, then print their 15% bonus.

You start with:

    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];

Build:

Alice Chen
Bonus: $37500

Rules:

  • Index i in all three vectors refers to the same employee.
  • The winner is whichever employee has the highest productivity. If two employees share the highest productivity, the one listed first wins.
  • The winner's bonus is 15% of their salary, rounded down to a whole number.
  • Print the winner's name on the first line, then "Bonus: $<amount>" on the second.

Start with let mut bestIndex = 0 and loop over the other indices with for i in 1..names.len(). Inside the loop, update the best index only when productivities[i] > productivities[bestIndex]: a strict comparison keeps the first employee on a tie.

Dividing two whole numbers (i32) drops the fraction, so salaries[bestIndex] * 15 / 100 is already rounded down: let bonus = salaries[bestIndex] * 15 / 100;

{} in the format string is replaced by the value: println!("Bonus: ${}", bonus);

    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);

STEP 1 OF 6
    Ctrl + Enter to check

    RUST · LOOPING OVER ARRAY INDICES

    Employee Of The Year V4 in Rust, explained

    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

    1. Create bestIndex with let mut and the value 0. It needs mut because the loop will change it.
    2. Loop over the remaining indexes. The range 1..names.len() starts at 1, since employee 0 is the starting champion, and stops before names.len(). For five employees the loop sees 1, 2, 3 and 4.
    3. Compare inside the loop. If productivities[i] is strictly greater than productivities[bestIndex], assign i to bestIndex.
    4. Compute the bonus after the loop from salaries[bestIndex], multiplying by 15 and then dividing by 100.
    5. Print the name names[bestIndex] on its own line.
    6. 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. bestIndex starts as the literal 0, and because it is used to index a vector, Rust infers usize for it. The loop variable i is a usize as well, so bestIndex = i type-checks. A usize can't hold a negative number.
    • Naming style. The names bestIndex follow the lesson's steps, but Rust's convention is snake case, best_index. The compiler prints a non_snake_case warning for bestIndex. It is a style warning only, and the program still runs.
    • vec! builds a vector. Its elements are the same type: &str for names and i32 by 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 bestIndex stays 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..1 is empty, the loop doesn't run, and employee 0 wins. That is correct.
    • No employees. The empty range 1..0 doesn't panic either, but salaries[bestIndex] then reads index 0 of an empty vector and the program panics with index 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(). If productivities were shorter, indexing it would panic.

    Testing

    • The lesson's data prints Alice Chen and Bonus: $37500.
    • Names A, B, C with productivities 100, 100, 90 and salaries 1000, 2000, 3000 print A and Bonus: $150.
    • Names A, B, C with productivities 1, 2, 3 and the same salaries print C and Bonus: $450.
    • A single employee A with salary 1000 prints A and Bonus: $150.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free