Start learning free

LESSON 185 OF 291 · LOOPING OVER ARRAY INDICES

Employee of the Year V4 in Kotlin: Finding the Best 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 = arrayOf("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = intArrayOf(83, 133, 97, 150, 120)
        val salaries = intArrayOf(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 in 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 = arrayOf("John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz")
        val productivities = intArrayOf(83, 133, 97, 150, 120)
        val salaries = intArrayOf(135000, 335000, 210000, 250000, 180000)

        var bestIndex = 0
        for (i in 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

    KOTLIN · LOOPING OVER ARRAY INDICES

    Employee Of The Year V4 in Kotlin, explained

    Problem overview

    A whole team competes now, and the data sits in three parallel arrays: names, productivities and salaries. Index i in all three arrays refers to the same employee. The program must find the employee with the highest productivity and print their name and their 15% bonus, rounded down. If two employees share the highest productivity, the one listed first wins.

    With these five employees:

    indexnameproductivitysalary
    0John Doe83135000
    1Mary Jane133335000
    2Bob Smith97210000
    3Alice Chen150250000
    4Carlos Diaz120180000

    Alice Chen has the highest productivity, 150, and 15% of 250000 is 37500:

    Alice Chen
    Bonus: $37500
    

    Approach

    The earlier versions used an if chain with one comparison per employee, which can't grow to a whole team. A loop can handle any number of employees with the same few lines.

    The technique is to keep the index of the best employee seen so far and challenge it with every other employee. Because all three arrays line up, one index gives you the name, the productivity and the salary. So the program stores a position, bestIndex, instead of copying a name and a salary into separate variables as the previous version did.

    Employee 0 is the best so far before anything is compared, since they are the only one seen. The loop then starts at index 1 and replaces bestIndex whenever it meets someone strictly more productive.

    Step by step

    1. Create bestIndex as a var set to 0. It is a var because the loop will change it.
    2. Loop over the other positions. for (i in 1 until names.size) makes i take the values 1, 2, 3 and 4. The upper bound of until is excluded, so names.size (5) never becomes an index.
    3. Compare inside the loop. If productivities[i] is strictly greater than productivities[bestIndex], set bestIndex = i. Strictly greater keeps the earlier employee on a tie.
    4. Calculate the bonus after the loop from salaries[bestIndex], multiplying by 15 and dividing by 100.
    5. Print the name at names[bestIndex].
    6. Print the bonus line, joining "Bonus: $" and the number with +.

    The solution in Kotlin

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

    How the loop runs

    Here is bestIndex after each pass, on the lesson's data:

    start bestIndex=0
    i=1 (133) bestIndex=1
    i=2 (97) bestIndex=1
    i=3 (150) bestIndex=3
    i=4 (120) bestIndex=3
    

    Employee 1 (133) beats employee 0 (83). Employee 2 (97) doesn't beat 133. Employee 3 (150) beats 133. Employee 4 (120) doesn't beat 150. The loop ends with bestIndex equal to 3, which is Alice Chen.

    Kotlin details

    • Two kinds of array. arrayOf("John Doe", ...) creates an Array<String>, and intArrayOf(83, ...) creates an IntArray, which holds primitive Int values without boxing. Both use [i] to read an element and .size for the length.
    • Ranges. 1 until names.size excludes the end. 1..names.size includes it, so the last pass would read index 5 and throw ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. names.indices is the range 0..4.
    • val and var. val arrays can still have their elements read and changed; only the variable's own binding is fixed. bestIndex is reassigned, so it is a var.
    • Integer division drops the fraction, so salaries[bestIndex] * 15 / 100 is already rounded down.

    Complexity

    The loop visits each employee once and does a constant amount of work for each, so the time is O(n) for n employees. The program stores only bestIndex and bonus beyond the input, so the extra space is O(1).

    Edge cases and common mistakes

    • Ties. If employees 0 and 3 both have productivity 150, the loop never replaces bestIndex at index 3, because 150 is not strictly greater than 150. Employee 0, John Doe, wins and the program prints Bonus: $20250. Using >= would give the win to the last tied employee.
    • A single employee. With one employee, 1 until 1 is an empty range, the loop body never runs and bestIndex stays 0. A team of one prints that employee's bonus, so starting at 0 and looping from 1 is safe. An empty team would fail at productivities[0].
    • Tracking the value instead of the index. Keeping the best productivity in a variable finds the highest number, but you then can't tell whose it is. The index gives you the name and the salary too.
    • Going out of range. Use until with size, not ...
    • Using the wrong array in the bonus. The bonus comes from salaries, not productivities.

    Testing

    Change the productivity values in the editor above and compare:

    productivitiesoutput
    83, 133, 97, 150, 120Alice Chen, Bonus: $37500
    150, 133, 97, 150, 120John Doe, Bonus: $20250
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free