Drill

ProblemsGo › payments

Split a bill without losing a kuruş

mediumpaymentsMathArraysGo

A table of friends splits the bill. The app has to hand out whole minor units that add back to exactly what was charged.

splitBill(total: int, people: int) → list<int>

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func splitBill(total int, people int) []int {
	
}

Worked examples

CallResult
splitBill(1000, 3)[]int{334, 333, 333}
splitBill(1000, 4)[]int{250, 250, 250, 250}
splitBill(10, 4)[]int{3, 3, 2, 2}
splitBill(0, 3)[]int{0, 0, 0}

Hint

Base share is total / people. The first (total % people) people pay one more.

Reference solution in Go
func splitBill(total int, people int) []int {
	if people <= 0 || total < 0 {
		return []int{}
	}
	base, extra := total/people, total%people
	shares := []int{}
	for i := 0; i < people; i++ {
		if i < extra {
			shares = append(shares, base+1)
		} else {
			shares = append(shares, base)
		}
	}
	return shares
}

The same problem in another language

More payments problems in Go