Start learning free

LESSON 185 OF 291 · LOOPING OVER ARRAY INDICES

Employee of the Year V4 in Scala: Max in Arrays with a for Loop

Practice Read the full explanation

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

You start with:

        val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = Array(83, 133, 97, 150, 120)
        val salaries = Array(135000, 335000, 210000, 250000, 180000)

Build:

Alice Chen
Bonus: $37500

Rules:

  • Index i in all three arrays 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 var bestIndex = 0 and loop over the other indices with for (i <- 1 until names.size). 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 (Int) drops the fraction, so salaries(bestIndex) * 15 / 100 is already rounded down: val bonus = salaries(bestIndex) * 15 / 100

+ turns the Int into text: println("Bonus: $" + bonus)

        val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = Array(83, 133, 97, 150, 120)
        val salaries = Array(135000, 335000, 210000, 250000, 180000)

        var bestIndex = 0
        for (i <- 1 until names.size) {
            if (productivities(i) > productivities(bestIndex)) {
                bestIndex = i
            }
        }
        val bonus = salaries(bestIndex) * 15 / 100
        println(names(bestIndex))
        println("Bonus: $" + bonus)

STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · LOOPING OVER ARRAY INDICES

    Employee Of The Year V4 in Scala, explained

    Problem overview

    The company now has five employees, stored in three parallel arrays: names, productivities and salaries. Index i in all three arrays describes the same person. The program finds the employee with the highest productivity and prints their name, then their bonus: 15% of their salary, rounded down. If two employees share the highest productivity, the one listed first wins.

    With the starter data, Alice Chen has the highest productivity, 150, and a salary of 250000. Her bonus is 250000 * 15 / 100, which is 37500:

    Alice Chen
    Bonus: $37500
    

    The earlier versions compared two or three employees with hand-written if chains. That doesn't scale, and a loop does the same work for any number of employees.

    Approach: remember the best position so far

    The idea is to scan the list once and keep the index of the best employee seen so far. Start by assuming employee 0 is the best. Then look at each other employee in turn, and whenever one has a strictly higher productivity than the current best, make that one the new best.

    Keeping the index rather than the productivity is deliberate. One index gives access to the name, the productivity and the salary, because the three arrays line up. If the loop only remembered the highest productivity number, it would not know whose name to print.

    The comparison is strictly greater, not greater-or-equal. When a later employee only ties the current best, the earlier one keeps the lead, which is exactly the tie rule. The loop starts at index 1, because employee 0 is already the starting best and comparing them with themselves would change nothing.

    Step by step

    1. Create bestIndex as a var set to 0. It must be a var, because the loop reassigns it.
    2. Write the loop header. for (i <- 1 until names.size) makes i take the values 1, 2, 3 and 4. The range 1 until 5 stops before 5. Write the closing brace straight away so the next steps go inside it.
    3. Compare inside the loop. An if checks whether productivities(i) is greater than productivities(bestIndex). If so, it assigns i to bestIndex.
    4. Compute the bonus after the loop. By then bestIndex is the winner's position, so salaries(bestIndex) * 15 / 100 is the winner's bonus. Integer division drops the fraction.
    5. Print the name, names(bestIndex), on its own line.
    6. Print the bonus line by joining "Bonus: $" and bonus with +.

    The solution in Scala

            val names = Array("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
            val productivities = Array(83, 133, 97, 150, 120)
            val salaries = Array(135000, 335000, 210000, 250000, 180000)
    
            var bestIndex = 0
            for (i <- 1 until names.size) {
                if (productivities(i) > productivities(bestIndex)) {
                    bestIndex = i
                }
            }
            val bonus = salaries(bestIndex) * 15 / 100
            println(names(bestIndex))
            println("Bonus: $" + bonus)
    

    Scala details worth knowing:

    • Arrays use parentheses. Scala reads an element with productivities(i), not square brackets. Square brackets are for type parameters, as in Array[Int].
    • until excludes the end. 1 until names.size is the list 1, 2, 3, 4. Writing 1 to names.size would include 5, and productivities(5) would throw an ArrayIndexOutOfBoundsException. names.size and names.length give the same number for an array.
    • The loop variable is a val. i is a fresh value in each round and can't be assigned to. bestIndex lives outside the loop, which is why it is the one declared as a var.
    • Int arithmetic. salaries(bestIndex) * 15 / 100 multiplies first and divides second. For these salaries the product fits easily in a 32-bit Int. Dividing by 100 first, as in salary / 100 * 15, would drop digits too early for salaries that are not multiples of 100.
    • "Bonus: $" is a plain string. The dollar sign has no special meaning unless the string starts with s, as in an interpolated string. Here it prints as it is, and + converts the Int to text.

    Following the loop

    The variable bestIndex starts at 0, productivity 83. Then the loop runs through these rounds:

    iProductivity at iCompared withbestIndex afterwards
    1133831
    2971331
    31501333
    41201503

    The winner is index 3, Alice Chen.

    Complexity

    Time: O(n), where n is the number of employees. The loop visits each employee once, and each visit does a constant amount of work. Space: O(1): the program stores one extra index and one bonus, however long the arrays are.

    Testing

    Keeping the names and salaries from the starter data and changing only the productivities:

    ProductivitiesOutput
    83, 133, 97, 150, 120Alice Chen, Bonus: $37500
    83, 150, 97, 150, 120Mary Jane, Bonus: $50250

    In the second row, Mary Jane and Alice Chen both have 150, and the earlier of the two wins. A single employee, Array("Solo") with productivity 10 and salary 100000, prints Solo and Bonus: $15000, because the loop range is empty and employee 0 stays the best.

    Edge cases and common mistakes

    • Using >= in the comparison. That would let a later employee replace an earlier one on a tie, and the second row above would print Alice Chen instead of Mary Jane.
    • Remembering the productivity instead of the index. The program would know the highest number but not the matching name or salary.
    • Declaring bestIndex as a val. The compiler rejects the assignment inside the loop, because a val can't be reassigned.
    • Looping to names.size inclusive. With 1 to names.size the last round reads past the end of the array and throws ArrayIndexOutOfBoundsException.
    • Empty arrays. With no employees at all, reading productivities(0) or names(0) throws the same exception, so this version assumes at least one employee.
    • Arrays of different lengths. The program trusts that the three arrays line up. If one is shorter, the loop eventually reads past its end.

    Key takeaways

    • Parallel arrays share an index, so one remembered index finds everything about the winner.
    • A scan that updates only on a strictly higher value keeps the first of several ties.
    • A loop handles any number of employees with the same code.
    • The next version builds on this one.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free