Created
February 23, 2018 19:27
-
-
Save gevann/eb087ad84d4157aa74907193aef6a6da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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