Find the bug · #30 · Numbers Hard JavaScript
Split bills don’t add up
Splitting a bill three ways loses a paisa, and the accounts never reconcile.
On this page
The report
Splitting a ₹10.00 bill three ways charges everyone ₹3.33. The restaurant is short a paisa on every bill like this, and the accounts don’t reconcile at the end of the month.
The code
Read it first: what should it do? Then click the line where you think the bug is.
// Splits a bill (in paise) between people, as evenly as possible.
function splitBill(totalPaise, people) {
const share = Math.floor(totalPaise / people);
return new Array(people).fill(share);
}Read it, then pick a line.
333 × 3 is how much? Where did the rest go?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
const shares = splitBill(1000, 3);
console.log(shares.join(' + '), '=', shares.reduce((a, b) => a + b, 0));It prints
333 + 333 + 333 = 999
It should print
334 + 333 + 333 = 1000
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 gives everyone the rounded-down share. When the total doesn’t divide evenly, the remainder (here 1 paisa) is simply dropped, so the shares add up to less than the bill. Hand the leftover paise out, one each, to the first few people.
The fix
1// Splits a bill (in paise) between people, as evenly as possible.2function splitBill(totalPaise, people) {3 const share = Math.floor(totalPaise / people);4 return new Array(people).fill(share);4 const extra = totalPaise % people;5 return Array.from({ length: people }, (_, i) => share + (i < extra ? 1 : 0));5}How you’d find it
- Reproduce and add the shares up: 333 × 3 = 999. One paisa short of 1,000.
- The shares are each rounded down, so whatever doesn’t divide evenly disappears:
1000 % 3is 1. - Write down what must always be true, then test it: the shares add up to the total, and no two differ by more than one paisa.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
for (const [total, n] of [[1000, 3], [100, 7], [5, 5], [7, 2]]) {
const shares = splitBill(total, n);
assert.equal(shares.reduce((a, b) => a + b, 0), total);
assert.ok(Math.max(...shares) - Math.min(...shares) <= 1);
}Where else this bites
- Spreading a discount across the lines of a cart, or GST across items.
- Splitting work into batches: the last batch has to take the leftovers.