Problem overview
Version 6 generalises the "best employee" search: instead of one winner, the top k most productive employees each get a bonus, where k is a variable. There is still no sorting. The program repeats the search for the best employee k times, and remembers who has already won so nobody wins twice.
The three arrays line up by index: names[i], productivities[i] and salaries[i] describe the same employee. The bonus is 15% of the salary, rounded down. With k = 3 the output is:
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
Alice Chen has the highest productivity (150), then Mary Jane (133), then Carlos Diaz (120). If two employees tie, the one listed first wins. If k is larger than the number of employees, everybody wins once and no extra lines are printed.
Approach: repeat the search, skipping earlier winners
Finding one maximum means scanning the list while keeping the position of the best employee so far. Doing that three times would find Alice Chen three times, so each round needs to ignore the people who already won. The lesson keeps an array taken with one boolean per employee: taken[i] is true once employee i has won.
That gives two nested loops. The outer loop counts rounds, one per winner. The inner loop is the search over all employees, skipping the taken ones. When the inner loop finishes, bestIndex holds the winner of the round, who is then marked as taken, so the next round finds the runner-up.
The cost is k scans of n employees, which is O(k * n) time with one extra array of n booleans. Sorting once would be faster for a large k, but this lesson practises nested loops, and for a small k the repeated scan is simple and fast.
Step by step
- Create
taken.new Array(names.length)makes an empty array that long, andfill(false)putsfalsein every slot. Nobody has won yet. - Write the outer loop.
rankgoes from 0 whilerank < k: one pass per winner. The counter only counts rounds. - Create
bestIndexinside the round withlet, starting at-1. No employee has index -1, so it means nobody is chosen yet. Because it is created inside the outer loop, every round starts afresh. - Write the inner loop over every position
iofnames. Each round looks at everybody again. - Write the condition. An employee becomes the round's best when they have not won (
!taken[i]) and either nobody is chosen yet (bestIndex === -1) or their productivity is strictly greater than the current best's. ThenbestIndexbecomesi. "Strictly greater" is what makes ties go to the employee listed first. - Check that someone was found. After the inner loop,
bestIndex !== -1. Ifkexceeds the number of employees, the last rounds find nobody and must print nothing. - Mark the winner by setting
taken[bestIndex]totrue, immediately, because the next round reads it. - Compute the bonus in a
const:Math.floor(salaries[bestIndex] * 15 / 100). - Print the winner as
name: $bonus.
The solution in JavaScript
const names = ["John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"];
const productivities = [83, 133, 97, 150, 120];
const salaries = [135000, 335000, 210000, 250000, 180000];
const k = 3;
const taken = new Array(names.length).fill(false);
for (let rank = 0; rank < k; rank++) {
let bestIndex = -1;
for (let i = 0; i < names.length; i++) {
if (!taken[i] && (bestIndex === -1 || productivities[i] > productivities[bestIndex])) {
bestIndex = i;
}
}
if (bestIndex !== -1) {
taken[bestIndex] = true;
const bonus = Math.floor(salaries[bestIndex] * 15 / 100);
console.log(names[bestIndex] + ": $" + bonus);
}
}
The details worth a closer look:
new Array(n).fill(false).new Array(3)alone is a sparse array with three empty slots, and reading a slot givesundefined.fill(false)makes every slot a realfalse.- Short-circuit evaluation. In
!taken[i] && (...), the parenthesised test only runs for employees who are still available. Inside it,bestIndex === -1 ||comes first, soproductivities[bestIndex]is never read whilebestIndexis -1. - The parentheses.
&&binds tighter than||. Without the parentheses, the!taken[i]test would apply only to the first of the two alternatives. $in a string. In an ordinary quoted string"$"is just a character. Joining with+turns the number into text.- Rounding.
salaries[bestIndex] * 15 / 100multiplies before it divides, andMath.floordrops the cents. Alice's 250000 gives exactly 37500.
Edge cases and common mistakes
klarger than the number of employees. Withk = 5every employee wins once and the output has five lines. Withk = 7the output is the same five lines. The rounds after the fifth find nobody,bestIndexstays -1, and the check skips them. Without the check,salaries[-1]would beundefined, and the program would printundefined: $NaN.- Ties. For names
["A", "B", "C"]with productivities[100, 100, 90]and salaries[1001, 2000, 333], A wins the first round and B the second, because the comparison is strict and A is listed first. - Rounding. A salary of 1001 gives 150.15, and 333 gives 49.95. The lesson's rule rounds down, so the bonuses are 150 and 49.
- Forgetting to mark the winner. Without
taken[bestIndex] = true, every round would pick Alice Chen again. - Declaring
bestIndexoutside the outer loop. It would keep the previous winner's index into the next round, and the=== -1test would never fire again. k = 0. The outer loop doesn't run and nothing is printed.
Testing
k = 3prints Alice Chen ($37500), Mary Jane ($50250) and Carlos Diaz ($27000).k = 1prints onlyAlice Chen: $37500.k = 2addsMary Jane: $50250.k = 5andk = 7print the same five lines: Alice Chen $37500, Mary Jane $50250, Carlos Diaz $27000, Bob Smith $31500 and John Doe $20250.
