Skip to content

Instantly share code, notes, and snippets.

@dustMason
Created September 27, 2017 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustMason/3050813a3c150d2465dd468cccb749f3 to your computer and use it in GitHub Desktop.
Save dustMason/3050813a3c150d2465dd468cccb749f3 to your computer and use it in GitHub Desktop.
Sarah, Alice, John, Bob
Sarah -400
---
Sarah -300
Alice 100
John 100
Bob 100
John -100
---
Sarah -300
Alice 150
John 0
Bob 150
class Ledger
def initialize names, values=[]
@ledger = {}
names.each.with_index do |name, i|
@ledger[name] = 0
@ledger[name] = values[i] unless values.empty?
end
end
def transaction amount, buyer, beneficiaries
@ledger[buyer] -= amount
share = amount / beneficiaries.size
beneficiaries.each { |person| @ledger[person] += share }
end
def report
payments = []
until @ledger.values.all? { |v| v == 0 } do
@ledger.each do |name, balance|
next if balance == 0
if balance < 0
payer_name, payer_balance = find_payer
amount = [balance*-1, payer_balance].min
@ledger[name] += amount
@ledger[payer_name] -= amount
payments << "#{payer_name} pays #{name} #{amount}"
end
end
end
payments
end
private
def find_payer
@ledger.find { |name, balance| balance > 0 }
end
end
ledger = Ledger.new %w{Alice Bob John Sarah}
ledger.transaction 400, 'Sarah', %w{Alice Bob John Sarah}
ledger.transaction 100, 'John', %w{Alice Bob}
#
# puts ledger.report
# ledger = Ledger.new %w{John Sarah Katie Sam Joseph Ben Charlie Fred}, [50, 125, 15, -7, -6, -9, -43, -125]
puts ledger.report
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment