Skip to content

Instantly share code, notes, and snippets.

@gevann
Created February 23, 2018 19:27
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 gevann/eb087ad84d4157aa74907193aef6a6da to your computer and use it in GitHub Desktop.
Save gevann/eb087ad84d4157aa74907193aef6a6da to your computer and use it in GitHub Desktop.
# Calculates what percentage of 'n' each element of 'arr' should have, by weight.
#
# @param arr [Array<#amount>] the array of objects to spread n across.
# @param n [Number] the amount to spread accross arr.
def adj(arr, n)
total = arr.inject(BigDecimal(0)) { |acc, memo| acc += memo.amount }
results = arr.map { |elem| (elem.amount / total).round(2) }
# ensure the last entry accounts for rounding
results[-1] = total - results[0...-1].inject(&:+)
arr.zip(results)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment