Skip to content

Instantly share code, notes, and snippets.

@sbstp
Last active August 29, 2015 13:55
Show Gist options
  • Save sbstp/8727058 to your computer and use it in GitHub Desktop.
Save sbstp/8727058 to your computer and use it in GitHub Desktop.
Determines who should give how much to who, accounting for each person's input
displayNum = (num) ->
return '' + Math.round(num * 100) / 100
class Person
constructor: (@name, @input) ->
@balance = 0
give: (other, amount) ->
@balance -= amount
other.balance += amount
console.log("%s gives %s $ to %s.", @name, displayNum(amount), other.name)
#
# setup stuff here
#
persons = [
new Person('justin', 38)
new Person('simon', 23)
new Person('félix', 10)
new Person('maxime', 10)
new Person('guillaume', 0)
]
totalInput = 0
for person in persons
totalInput += person.input
avgInput = totalInput / persons.length
console.log('The total amount is %s $ therefore, everyone should pay %s $.', displayNum(totalInput), displayNum(avgInput))
aboves = []
belows = []
for person in persons
person.balance = avgInput - person.input
if person.balance > 0 then aboves.push(person)
else if person.balance < 0 then belows.push(person)
above = aboves.shift()
below = belows.shift()
while below && above
amount = Math.min(above.balance, Math.abs(below.balance))
above.give(below, amount)
if above.balance == 0 then above = aboves.shift()
if below.balance == 0 then below = belows.shift()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment