Problem overview
The final version of the project gives bonuses to the top k most productive employees, where k is a variable. The data is three parallel slices, so index i in each one is the same person, plus k:
names := []string{"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"}
productivities := []int{83, 133, 97, 150, 120}
salaries := []int{135000, 335000, 210000, 250000, 180000}
k := 3
Each bonus is 15% of the salary, rounded down. The program prints one line per winner, best first, as name: $bonus. On a tie in productivity the employee listed first wins. The output for k = 3 is:
Alice Chen: $37500
Mary Jane: $50250
Carlos Diaz: $27000
The program must keep working when k changes. If k is larger than the number of employees, everybody wins once, and the extra rounds print nothing.
Approach: repeat the search, remember the winners
The lesson doesn't sort. Instead it repeats the search for the best employee k times. A single search is a loop that keeps the index of the best candidate so far and replaces it only when it finds a strictly higher productivity, so ties stay with the earlier employee. Repeating it alone would find Alice Chen every time. To make each round find the next best, the program keeps a bool flag for each employee: taken[i] says that employee i has already won. Each round skips the taken employees, and the winner of the round is marked as taken.
Each round starts a new search with bestIndex at -1, meaning nobody chosen yet. It can't start at 0, because employee 0 may already be taken, and the search must not compare against a winner from an earlier round. An employee becomes the round's best if they are not taken, and either nobody is chosen yet or their productivity is strictly higher than the current best's.
After the search, bestIndex is still -1 only if every employee is taken. That happens when k is larger than the number of employees, and in that case the round prints nothing.
On the starting data the three rounds pick Alice Chen (150), Mary Jane (133) and Carlos Diaz (120), in that order.
Step by step
- Create
taken.make([]bool, len(names))makes a slice with oneboolper employee, allfalse. - Write the rounds loop.
for rank := 0; rank < k; rank++ {runsktimes. The counter only counts the rounds. Close the brace right away. - Start the round with
bestIndex := -1. It is declared inside the loop, so every round starts with nobody chosen. - Write the inner loop over
ifrom 0 tolen(names). It looks at everybody every time, and the taken ones are skipped in the next step. - Write the condition.
!taken[i], and eitherbestIndex == -1orproductivities[i] > productivities[bestIndex]. When it holds, assignbestIndex = i. - Check that somebody was found, with
if bestIndex != -1, after the inner loop. This guards the rounds whenkis too large. - Mark the winner by setting
taken[bestIndex]totrue. It must happen right away, because the next round reads it. - Compute
bonusfrom the winner's salary:salaries[bestIndex] * 15 / 100. Multiplying before dividing keeps the precision, and integer division rounds the result down. - Print the winner as the name,
": $"and the bonus converted withstrconv.Itoa.
The solution in Go
names := []string{"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"}
productivities := []int{83, 133, 97, 150, 120}
salaries := []int{135000, 335000, 210000, 250000, 180000}
k := 3
taken := make([]bool, len(names))
for rank := 0; rank < k; rank++ {
bestIndex := -1
for i := 0; i < len(names); i++ {
if !taken[i] && (bestIndex == -1 || productivities[i] > productivities[bestIndex]) {
bestIndex = i
}
}
if bestIndex != -1 {
taken[bestIndex] = true
bonus := salaries[bestIndex] * 15 / 100
fmt.Println(names[bestIndex] + ": $" + strconv.Itoa(bonus))
}
}
The code uses the fmt and strconv packages. A few Go details:
- Zero values.
make([]bool, n)fills the slice withfalse, the zero value ofbool. No loop is needed to initialise it. - Short-circuit operators.
&&and||stop as soon as the answer is known. WhenbestIndex == -1is true, the right side of the||is never evaluated, soproductivities[bestIndex]with index -1 is not read. The order of the two tests matters here. Indexing a slice at -1 panics at run time. - Precedence.
&&binds tighter than||, so the parentheses around the||part are needed. Without them the condition would mean something else: "not taken and nobody chosen yet, or a higher productivity". - Slices are mutable in place.
taken[bestIndex] = truechanges the slice that the next round reads. - Money as
int.salaries[bestIndex] * 15 / 100is integer arithmetic on whole numbers. Go evaluates*and/from left to right, so the multiplication happens first. $is just a character inside the string": $".
Complexity
Time is O(k * n) for n employees: each of the k rounds scans all n. When k is much larger than n, the extra rounds still scan everybody and find nobody, so the cost is still k * n operations, though nothing is printed. Sorting would cost O(n log n), which is better when k is large, but this lesson practises the repeated search. Space is O(n) for the taken slice.
Edge cases and common mistakes
- No
takenflags. Every round finds the same employee: two rounds without the flags both print Alice Chen. klarger than the team. Withk = 7and five employees, the output is five lines, from Alice Chen down to John Doe. The guardbestIndex != -1is what stops the sixth round. Without it,taken[bestIndex]panics withindex out of range [-1].- Starting
bestIndexat 0. In the later rounds employee 0 may be taken, and the search would start from a winner. - Ties. With productivities 100, 100, 100 and 90, the first three rounds pick the employees in listed order, so a tie never reorders them. The comparison must be strict (
>). - Declaring
bestIndexoutside the rounds loop. It would keep the previous winner and never be reset. kof 0. The loop doesn't run and nothing is printed.- Rounding. A salary of 100001 gives a bonus of 15000, not 15000.15, because the division drops the fraction.
Testing
With the starting data and different values of k:
k = 1printsAlice Chen: $37500.k = 2prints that line andMary Jane: $50250.k = 5prints Alice Chen, Mary Jane, Carlos Diaz ($27000), Bob Smith ($31500) and John Doe ($20250).k = 7prints the same five lines ask = 5.k = 0prints nothing.
