Skip to content

Instantly share code, notes, and snippets.

@marsbomber
Created December 18, 2012 05:30
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 marsbomber/4325320 to your computer and use it in GitHub Desktop.
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%
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