Start learning free

LESSON 188 OF 410 · NESTED LOOPS

Employee of the Year V6 - Project in Java

Practice

Generalize the previous version: give bonuses to the top K most productive employees, where k is given as a variable. Still no sorting: repeat the search for the best employee k times, and remember who already won so nobody wins twice.

You start with:

String[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
int[] productivities = {83, 133, 97, 150, 120};
int[] salaries = {135000, 335000, 210000, 250000, 180000};
int k = 3;

Build:

Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000

Rules:

  • Index i in all three arrays refers to the same employee.
  • Round 1 finds the employee with the highest productivity, round 2 the best among the employees who have not won yet, and so on, for k rounds.
  • 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 one line per winner, best first: name: $bonus.
  • If k is larger than the number of employees, everybody wins once and you print one line per employee: when nobody is left, a round prints nothing.
  • Your code must keep working when k changes to 1, 2, 5 or 7.

Use a list of booleans: boolean[] taken = new boolean[names.length];. A round finds the best employee among those who are not taken yet, then marks that employee as taken.

The outer loop runs k times and the inner loop is the search from v4 with one more condition: if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {. If nobody is found in a round, skip the rest of that round.

String[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
int[] productivities = {83, 133, 97, 150, 120};
int[] salaries = {135000, 335000, 210000, 250000, 180000};
int k = 3;

boolean[] taken = new boolean[names.length];
for (int rank = 0; rank < k; rank++) {
    int bestIndex = -1;
    for (int i = 0; i < names.length; i++) {
        if (!taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex])) {
            bestIndex = i;
        }
    }
    if (bestIndex != -1) {
        taken[bestIndex] = true;
        int bonus = salaries[bestIndex] * 15 / 100;
        System.out.println(names[bestIndex] + ": $" + bonus);
    }
}

STEP 1 OF 9
    Ctrl + Enter to check

    Employee Of The Year V6 in Java

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free