Start learning free

LESSON 186 OF 292 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in Swift: Top Two Without Sorting

Practice Read the full explanation

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

You start with:

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three arrays refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (with integer division).
  • Print two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex]) {. "Nobody chosen yet" must also let an employee in.

        let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
        let productivities = [83, 133, 97, 150, 120]
        let salaries = [135000, 335000, 210000, 250000, 180000]

        var bestIndex = 0
        for i in 1..<names.count {
            if productivities[i] > productivities[bestIndex] {
                bestIndex = i
            }
        }
        var secondIndex = -1
        for i in 0..<names.count {
            if i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex]) {
                secondIndex = i
            }
        }
        let bestBonus = salaries[bestIndex] * 15 / 100
        let secondBonus = salaries[secondIndex] * 15 / 100
        print(names[bestIndex] + ": $" + String(bestBonus))
        print(names[secondIndex] + ": $" + String(secondBonus))

STEP 1 OF 10
    Ctrl + Enter to check

    SWIFT · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in Swift, explained

    Problem overview

    This version awards bonuses to the two most productive employees: the best first, then the second best. The data is still three parallel arrays, names, productivities and salaries, where index i describes one employee. On equal productivity, the employee listed first ranks higher. Each bonus is 15% of the salary, rounded down. The program prints two lines in the form name: $bonus.

    For the starter data the best is Alice Chen (150) and the second is Mary Jane (133):

    Alice Chen: $37500
    Mary Jane: $50250
    

    The first loop is the one from the previous version. This version adds a second loop for second place.

    Approach: two scans, the second skipping the winner

    Sorting the arrays would put the top two first, but the three arrays would have to be reordered together, and the lesson asks for no sorting. Two linear scans are simpler.

    The first scan finds bestIndex with a running champion that is replaced only on a strictly higher productivity. The second scan finds the best among the others: it looks at every index, ignores bestIndex, and keeps a running champion of its own, secondIndex.

    The second scan has a starting problem. In the first scan, index 0 could safely be the first champion. Here, index 0 might be the overall best, which is not allowed to be second. So secondIndex starts at -1, meaning nobody is chosen yet. No array has an element at index -1, so the value can't be confused with a real employee. The scan then reads: take employee i if it is not the best one and either nobody is chosen yet or its productivity is strictly higher than the current second's.

    The second loop on the starter data

    isecondIndex after the checkWhy
    00Nobody chosen yet.
    11133 is higher than 83.
    2197 is not higher than 133.
    31This is the best employee, so it is skipped.
    41120 is not higher than 133.

    Step by step

    1. Create bestIndex as a var starting at 0.
    2. Loop over 1..<names.count to visit every other employee.
    3. Replace the champion on a strictly higher productivity. Strict means the first listed wins ties.
    4. Create secondIndex as a var starting at -1, the "nobody yet" marker.
    5. Start a second loop over 0..<names.count. It begins at 0 because the best employee can be anywhere, and that one is skipped inside the loop.
    6. Write the condition: i differs from bestIndex, and either secondIndex is -1 or the productivity at i is strictly greater than the one at secondIndex. When it holds, set secondIndex to i.
    7. Compute bestBonus from salaries[bestIndex].
    8. Compute secondBonus the same way from secondIndex.
    9. Print the best employee: the name, a colon, a dollar sign and the bonus, with String(...) turning the number into text.
    10. Print the second best in the same form on the next line.

    The solution in Swift

            let names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"]
            let productivities = [83, 133, 97, 150, 120]
            let salaries = [135000, 335000, 210000, 250000, 180000]
    
            var bestIndex = 0
            for i in 1..<names.count {
                if productivities[i] > productivities[bestIndex] {
                    bestIndex = i
                }
            }
            var secondIndex = -1
            for i in 0..<names.count {
                if i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex]) {
                    secondIndex = i
                }
            }
            let bestBonus = salaries[bestIndex] * 15 / 100
            let secondBonus = salaries[secondIndex] * 15 / 100
            print(names[bestIndex] + ": $" + String(bestBonus))
            print(names[secondIndex] + ": $" + String(secondBonus))
    

    The Swift details worth knowing:

    • Short-circuit || and &&. When secondIndex == -1 is true, Swift does not evaluate the right side of the ||, so productivities[secondIndex] never runs with an index of -1. The order of the two checks is what keeps the code safe, since productivities[-1] would crash. The parentheses are needed too: without them, && would bind tighter than || and change the meaning.
    • A sentinel value. Using -1 for "none" works because it is not a valid index. Swift's optional type, Int?, is the other way to say "maybe nothing", but the lesson uses the sentinel.
    • != on integers. i != bestIndex compares two Int values and gives a Bool.
    • Two separate loops. Each for declares its own i, which exists only inside that loop, so the two loops don't interfere.

    Edge cases and common mistakes

    • A tie for the top. With productivities [83, 150, 97, 150, 120], Mary Jane and Alice Chen both have 150. The best is Mary Jane, who is listed first. The second scan skips her, and Alice Chen is the best of the rest, so the output is Mary Jane: $50250 then Alice Chen: $37500.
    • Exactly two employees. With John Doe (83) and Mary Jane (133) only, the output is Mary Jane: $50250 then John Doe: $20250.
    • Fewer than two employees. With one employee, the second loop skips the only index, secondIndex stays -1, and salaries[secondIndex] crashes at run time. The lesson's data always has at least two.
    • Starting secondIndex at 0. If the best employee is at index 0, the second place would start as the best employee, and the scan would never remove them. The marker -1 avoids that.
    • Forgetting to skip the best index. The second scan would then find the same employee again, and the output would list the winner twice.
    • Starting the second loop at 1. That would never consider employee 0, who can be second.
    • Leaving out the -1 check. The first eligible employee has no previous second to compare with, so that case must be accepted without a comparison.

    Testing

    • The starter data prints Alice Chen: $37500 then Mary Jane: $50250.
    • With productivities [83, 150, 97, 150, 120], the output is Mary Jane: $50250 then Alice Chen: $37500.
    • With only John Doe and Mary Jane (productivities 83 and 133), the output is Mary Jane: $50250 then John Doe: $20250.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free