例如,我有以下数据:
headings = {
:heading1 => { :weight => 60, :show_count => 0}
:heading2 => { :weight => 10, :show_count => 0}
:heading3 => { :weight => 20, :show_count => 0}
:heading4 => { :weight => 10, :show_count => 0}
}
total_views = 0
现在我想根据他们的体重来发球。例如,对于前10个请求/迭代,
heading1
、heading3
、heading2
和heading4
将按顺序(按权重)分别被服务6、2、1和1次。对于每个迭代,服务标题的show_计数将增加1,并且全局的total_视图也将增加。
你能推荐一个算法或者一些ruby代码来处理这个问题吗?
最佳答案
这应该适用于您的基本情况,并且可以根据您需要的详细信息进行修改:
class Heading
attr_reader :heading, :weight, :show_count
def initialize(heading,weight=1)
@heading=heading
@weight=weight
@show_count=0
end
def serve
puts "Served #{@heading}! "
@show_count += 1
end
end
class HeadingServer
attr_reader :headings
def initialize(headings_hash)
@headings=headings_hash.map {|h, data| Heading.new(h,data[:weight])}
@total_weight=@headings.inject(0) {|s,h| s+= h.weight}
end
def serve(num_to_serve=@total_weight)
@headings.sort {|a,b| b.weight <=> a.weight}.each do |h|
n = (h.weight * num_to_serve) / @total_weight #possibility of rounding errors
n.times { h.serve }
end
end
def total_views
@headings.inject(0) {|s,h| s += h.show_count}
end
end
headings = {
:heading1 => { :weight => 60, :show_count => 0},
:heading2 => { :weight => 10, :show_count => 0},
:heading3 => { :weight => 20, :show_count => 0},
:heading4 => { :weight => 10, :show_count => 0}
}
# Example Usage:
hs = HeadingServer.new(headings)
hs.serve(10)
hs.headings.each {|h| puts "#{h.heading} : served #{h.show_count} times"}
puts "Total Views: #{hs.total_views}"