TryBugHunt
goOff-by-oneMedium

Split bill charges the group an extra cent

BugFind the bug and fix the code

What it should do

splitBill(totalCents, people) divides a bill so the shares add up to exactly totalCents. The leftover cents go one each to the first people in the list. splitBill(1000, 3) returns [334, 333, 333].

What happens instead

splitBill(1000, 3) returns [334, 334, 333], which adds up to 1001 cents. splitBill(900, 3) returns [301, 300, 300].

package main

func splitBill(totalCents int, people int) []int {
    shares := make([]int, people)
    base := totalCents / people
    remainder := totalCents % people
    for i := range shares {
        shares[i] = base
    }
    for i := 0; i <= remainder; i++ {
        shares[i]++
    }
    return shares
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the off-by-one errors pattern

The loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

What you'll practise

A medium Go debugging exercise about off-by-one errors: the loop that runs one time too many, the slice that drops the last item, the index that starts in the wrong place.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

remainder is the number of cents left after everyone gets base, so exactly remainder people should get one more. A loop from 0 while i <= remainder runs remainder + 1 times, handing out a cent that does not exist. Even an exact split like 900 / 3 gets an extra cent, because the loop still runs once with remainder 0. A loop meant to run n times is for i := 0; i < n; i++. When money is involved, add the results back up in a test: the sum must equal the input.

The pattern behind it: off-by-one errors.

More off-by-one errors to practise

Related errors

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/80fa4e69-b998-4974-a970-0d943ce3c927" title="Debugging challenge: Split bill charges the group an extra cent" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/80fa4e69-b998-4974-a970-0d943ce3c927">TryBugHunt</a></p>