secret
Last active — forked from voxdei/fair_distribution.rb

Solution for RPCFN: Fair Distribution (#6) G.Petit

  • Download Gist
fair_distribution.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
# Author : Guillaume Petit
# Forked by Benoit Daloze
 
class Array
def sum
inject(0) { |sum, e| sum + e }
end
end
 
class FairDistribution
attr_reader :distribution
 
def initialize(jobs, nb_of_presses)
@jobs = jobs.sort.reverse # The longest jobs first
@distribution = Array.new(nb_of_presses) { [] }
 
@ideal_balance = @jobs.sum.to_f / nb_of_presses
 
balance # the real deal
end
 
def time_required
@distribution.map(&:sum).max
end
 
private
def balance
@jobs.each { |job| find_place_for(job) }
end
 
# try to find a place (distribution) by first looking for an "ideal" place
# and if not found, use the smallest simulated time
def find_place_for(job)
if ideal = @distribution.find { |press| press.sum + job == @ideal_balance }
puts :ideal
ideal << job
else
@distribution.min_by(&:sum) << job
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.