Skip to content

Instantly share code, notes, and snippets.

@eregon
Forked from voxdei/fair_distribution.rb
Created February 22, 2010 12:03
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 eregon/a2ccccc0fbcfccd6d0f5 to your computer and use it in GitHub Desktop.
Save eregon/a2ccccc0fbcfccd6d0f5 to your computer and use it in GitHub Desktop.
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