Skip to content

Instantly share code, notes, and snippets.

@philk
Created January 28, 2010 02:54
Show Gist options
  • Save philk/288393 to your computer and use it in GitHub Desktop.
Save philk/288393 to your computer and use it in GitHub Desktop.
hawkbook rubychallenge/rc6 ruby-1.9.1-p376» ruby test_solution_acceptance.rb full
Loaded suite test_solution_acceptance
Started
.....
Finished in 0.005828 seconds.
5 tests, 8 assertions, 0 failures, 0 errors, 0 skips
class Array
def sum
self.inject(0) { |x,n| x+n }
end
end
class FairDistribution
attr_accessor :jobs, :queues, :presses, :fair_time, :sort_method, :try_method
def initialize(jobs, presses)
@queues = Array.new
@fair_time = (jobs.sum.to_f / presses.to_f).ceil
@presses = presses
@presses.times { @queues.push(FairQueue.new) }
@jobs = jobs
@sort_method = :worstfit
@try_method = :all
try_all
end
def initialize_copy(fd)
fd.queues = Array.new
fd.presses.times { fd.queues.push(FairQueue.new) }
end
def try_all
worst_fit = [try_map, try_sort, try_reverse]
@sort_method = :bestfit
best_fit = [try_map, try_sort, try_reverse]
all_array = worst_fit + best_fit
best_fd = all_array.min {|a,b| a.time_required <=> b.time_required }
# puts "Best Sort: #{best_fd}"
# all_array.each { |a| puts "Times #{a.inspect} || #{a.time_required}"}
self.queues = best_fd.queues
self.try_method = best_fd.try_method
end
def try_map
fd = self.dup
fd.jobs.map do |j|
nq = fd.next_queue(j)
nq.jobs.push(j)
end
fd.try_method = :map
return fd
end
def try_sort
fd = self.dup
fd.jobs.sort.map do |j|
nq = fd.next_queue(j)
nq.jobs.push(j)
end
fd.try_method = :sort
return fd
end
def try_reverse
fd = self.dup
@jobs.sort.reverse.map do |j|
nq = fd.next_queue(j)
nq.jobs.push(j)
end
fd.try_method = :reverse
return fd
end
def next_queue(job_size)
fullest = @queues.max {|a,b| a.queue_time <=> b.queue_time }
emptiest = @queues.min {|a,b| a.queue_time <=> b.queue_time }
if (fullest.jobs.sum + job_size) <= @fair_time && @sort_method == :bestfit
return fullest
else
return emptiest
end
end
def time_required
@queues.map { |q| q.queue_time }.max
end
def distribution
@queues.map { |q| q.jobs }
end
end
class FairQueue
attr_accessor :jobs
def initialize
@jobs = Array.new
end
def queue_time
@jobs.sum
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment