Create a gist now

Instantly share code, notes, and snippets.

Solution for RPCFN: Fair Distribution (#6) G.Petit
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment