11. Split a Restaurant Bill Fairly

MediumJavaScriptPayments

A group-dining app lets friends scan the receipt and tag who shared each dish. Splitting "evenly" is not fair when one person only had a drink, and naive percentage maths produces shares that are off by a piaster, so the restaurant's card terminal rejects the split.

The app splits each dish among the people who shared it, then spreads VAT and tip in proportion to what each person ate. The shares must add up exactly to the bill.

Your task: Write splitBill(people, items, vatPercent, tipPercent) and return { [name]: amount } for every person, in piasters.

Rules: 1. Each item { name, price, sharedBy } is split equally among sharedBy. Leftover piasters go one each to the first people in sharedBy. 2. food = the sum of all prices. extra = round(food x vatPercent / 100) + round(food x tipPercent / 100). Round each part half up separately. 3. Split extra in proportion to each person's food share with the largest-remainder method: everyone first gets the floor of their exact share (extra x share / food), then the leftover piasters go one each to the people with the largest fractional parts. Ties go in people order. 4. People who shared nothing owe 0.

Notes: - Keep everything in integers: the fractional part of extra x share / food can be compared using the remainder (extra x share) % food.

Examples

Example 1

Input
  • people = ["Ali", "Mona", "Omar"]
  • items = [
      { name: "Pizza", price: 3001, sharedBy: ["Ali", "Mona", "Omar"] },
      { name: "Drink", price: 500, sharedBy: ["Mona"] }
    ]
  • vatPercent = 14
  • tipPercent = 10
Output
  • { Ali: 1241, Mona: 1860, Omar: 1240 }
Explanation
Food shares are 1001, 1500 and 1000 (Ali gets the extra piaster). extra = 490 + 350 = 840, split as 240, 360 and 240. The total is 4341, exactly the bill.

Solution

Write splitBill. Tab indents (Esc then Tab leaves the editor), Ctrl/⌘ + Enter runs. Each run has a 3-second limit. Your code is saved in this browser.

Test Results

Click "Run Code" to test your solution.