Skip to content

Instantly share code, notes, and snippets.

@takehiko
Created November 23, 2016 21:28
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 takehiko/a3e8594ad8fba0e9d5c3ace971293e28 to your computer and use it in GitHub Desktop.
Save takehiko/a3e8594ad8fba0e9d5c3ace971293e28 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# prorate.rb by takehikom
$show_midflow = true
class Array
def prorate(alloc = 100, permit_float = false)
s = self.inject(:+)
return self.dup if s == alloc
a2 = self.map { |v| v.to_f * alloc / s }
return a2 if permit_float
a3 = a2.map { |v| v.to_i }
a4 = a2.map { |v| v - v.to_i }
while a3.inject(:+) < alloc
i = a4.find_index(a4.max)
a3[i] += 1
a4[i] = 0
end
a3
end
end
def print_prorate(a)
print a.inspect, " => "
print a.prorate(100, true).inspect, " => " if $show_midflow
print a.prorate(100).inspect
puts
end
if __FILE__ == $0
if !ARGV.empty? && /test/ !~ ARGV.first
a = ARGV.map {|item| item.to_i}
# a = ARGV.map {|item| item.to_f}
print_prorate(a)
else
print_prorate([100, 200, 300, 400])
print_prorate([1, 1, 1, 1])
print_prorate([1, 1, 1, 3])
print_prorate([1, 1, 2, 3])
srand(12345)
print_prorate([rand(100) + 1, rand(100) + 1, rand(100) + 1, rand(100) + 1])
end
end
=begin
$ ruby prorate.rb
[100, 200, 300, 400] => [10.0, 20.0, 30.0, 40.0] => [10, 20, 30, 40]
[1, 1, 1, 1] => [25.0, 25.0, 25.0, 25.0] => [25, 25, 25, 25]
[1, 1, 1, 3] => [16.666666666666668, 16.666666666666668, 16.666666666666668, 50.0] => [17, 17, 16, 50]
[1, 1, 2, 3] => [14.285714285714286, 14.285714285714286, 28.571428571428573, 42.857142857142854] => [14, 14, 29, 43]
[99, 30, 2, 37] => [58.92857142857143, 17.857142857142858, 1.1904761904761905, 22.023809523809526] => [59, 18, 1, 22]
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment