/fair_distribution.rb Secret
Created
February 22, 2010 12:03
-
-
Save eregon/a2ccccc0fbcfccd6d0f5 to your computer and use it in GitHub Desktop.
Solution for RPCFN: Fair Distribution (#6) G.Petit
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
# 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