Last active
August 18, 2016 22:09
-
-
Save alexdunae/432a369baf364c0b6a8fa4a052e28b0a 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
# from https://github.com/drKreso/guerrilla_patch | |
class Allocate | |
attr_accessor :amount | |
attr_accessor :ratios | |
def self.evenly(amount, number_of_slices) | |
Allocate.new.tap do |a| | |
a.amount = amount | |
a.ratios = (1..number_of_slices).map { 1.to_d/number_of_slices } | |
end.divided | |
end | |
def initialize(amount = 0 , ratios = []) | |
@amount = amount | |
@ratios = ratios | |
end | |
def divided | |
divided_ratios = @ratios.map { |ratio| ratio.to_d/ array_sum(ratios).to_d } | |
rates = divided_ratios.map { |ratio| ((@amount * ratio).round(2)) } | |
compensate_last_slice(rates) | |
end | |
def compensate_last_slice(rates) | |
rates.tap do |rates| | |
max_rate = rates.max.abs | |
rates[-1] = (rates[-1] + (amount - array_sum(rates))).round(2) | |
if rates[-1].abs > (2 * max_rate.abs ) | |
raise "Number is too small to be allocated on that number of slices(#@amount on #{@ratios.size} slices)." | |
end | |
end | |
end | |
def array_sum(array) | |
array.reduce(0, :+) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment