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
- Create
bestIndexas avarset to 0. It must be avar, because the loop reassigns it. - Write the loop header.
for (i <- 1 until names.size)makesitake the values 1, 2, 3 and 4. The range1 until 5stops before 5. Write the closing brace straight away so the next steps go inside it. - Compare inside the loop. An
ifchecks whetherproductivities(i)is greater thanproductivities(bestIndex). If so, it assignsitobestIndex. - Compute the bonus after the loop. By then
bestIndexis the winner's position, sosalaries(bestIndex) * 15 / 100is the winner's bonus. Integer division drops the fraction. - Print the name,
names(bestIndex), on its own line. - Print the bonus line by joining
"Bonus: $"andbonuswith+.
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 inArray[Int]. untilexcludes the end.1 until names.sizeis the list 1, 2, 3, 4. Writing1 to names.sizewould include 5, andproductivities(5)would throw anArrayIndexOutOfBoundsException.names.sizeandnames.lengthgive the same number for an array.- The loop variable is a
val.iis a fresh value in each round and can't be assigned to.bestIndexlives outside the loop, which is why it is the one declared as avar. - Int arithmetic.
salaries(bestIndex) * 15 / 100multiplies first and divides second. For these salaries the product fits easily in a 32-bitInt. Dividing by 100 first, as insalary / 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 withs, as in an interpolated string. Here it prints as it is, and+converts theIntto text.
Following the loop
The variable bestIndex starts at 0, productivity 83. Then the loop runs through these rounds:
i | Productivity at i | Compared with | bestIndex afterwards |
|---|---|---|---|
| 1 | 133 | 83 | 1 |
| 2 | 97 | 133 | 1 |
| 3 | 150 | 133 | 3 |
| 4 | 120 | 150 | 3 |
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:
| Productivities | Output |
|---|---|
| 83, 133, 97, 150, 120 | Alice Chen, Bonus: $37500 |
| 83, 150, 97, 150, 120 | Mary 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
bestIndexas aval. The compiler rejects the assignment inside the loop, because avalcan't be reassigned. - Looping to
names.sizeinclusive. With1 to names.sizethe last round reads past the end of the array and throwsArrayIndexOutOfBoundsException. - Empty arrays. With no employees at all, reading
productivities(0)ornames(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.
