def queue_time(time_required, n)
remaining_time_by_line = Array.new(n) { 0 }
curr_time = 0
time_required.each do |t|
wait_time, line_assigned = remaining_time_by_line.each_with_index.min_by(&:first)
curr_time += wait_time
remaining_time_by_line.map! { |rt| rt - wait_time }
remaining_time_by_line[line_assigned] = t
end
curr_time + remaining_time_by_line.max
end
queue_time([5,3,4], 1)
#=> 12
queue_time([10,2,3,3], 2)
#=> 10
queue_time([2,3,10], 2)
#=> 12
queue_time([2,3,4,1,2,5], 3)
#=> 8
queue_time([751, 304, 2, 629, 36, 674, 1], 2)
#=> 1461
puts
在用语句加盐之后,我可以通过执行该方法来最容易地解释计算。
def queue_time(time_required, n)
remaining_time_by_line = Array.new(n) { 0 }
curr_time = 0
time_required.each do |t|
wait_time, line_assigned = remaining_time_by_line.each_with_index.min_by(&:first)
curr_time += wait_time
puts "\ntime required, t = #{t}"
puts "line_assigned = #{line_assigned}"
puts "wait_time = #{wait_time}"
puts "curr_time = #{curr_time}"
remaining_time_by_line.map! { |rt| rt - wait_time }
remaining_time_by_line[line_assigned] = t
puts "remaining_times_by_line = #{remaining_time_by_line}"
end
puts "\nremaining_time_by_line.max = #{remaining_time_by_line.max}"
tot = curr_time + remaining_time_by_line.max
puts "curr_time + remaining_time_by_line.max = #{tot}"
tot
end
queue_time([2,3,4,1,2,5], 3)
#=> 8
显示以下内容。
time required, t = 2
line_assigned = 0
wait_time = 0
curr_time = 0
remaining_times_by_line = [2, 0, 0]
time required, t = 3
line_assigned = 1
wait_time = 0
curr_time = 0
remaining_times_by_line = [2, 3, 0]
time required, t = 4
line_assigned = 2
wait_time = 0
curr_time = 0
remaining_times_by_line = [2, 3, 4]
time required, t = 1
line_assigned = 0
wait_time = 2
curr_time = 2
remaining_times_by_line = [1, 1, 2]
time required, t = 2
line_assigned = 0
wait_time = 1
curr_time = 3
remaining_times_by_line = [2, 0, 1]
time required, t = 5
line_assigned = 1
wait_time = 0
curr_time = 3
remaining_times_by_line = [2, 5, 1]
remaining_time_by_line.max = 5
curr_time + remaining_time_by_line.max = 8