Created
December 18, 2012 05:30
-
-
Save marsbomber/4325320 to your computer and use it in GitHub Desktop.
Given an array of INTs, calculate each INT's percentage contribution towards the sum of all INTs. Rounding needs to be done so that output floats can sum to a perfect 100%
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
def percentagerize(collection, result=[], remainder=1) | |
collection = Array(collection) | |
return result if collection.count == 0 | |
denominator = collection.inject(:+) | |
percent = 0.0 | |
unless denominator == 0 | |
percent = (remainder * (collection[0] / denominator.to_f)).round(4) | |
remainder -= percent | |
end | |
percentagerize(collection[1..-1], result << percent, remainder) | |
end | |
puts percentagerize([0, 1, 3, 1, 0, 0]).inspect | |
puts percentagerize([0, 1, 3, 1, 0]).inspect | |
puts percentagerize([1, 1, 3, 1, 0]).inspect | |
puts percentagerize([]).inspect | |
puts percentagerize(1).inspect | |
puts percentagerize(nil).inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment