重量随机项目 [英] Random item by weight
问题描述
例如我有这样的数据:
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
现在我想为每个标题基于其weightages。例如,对于前10个请求/迭代,标题1
, heading3
, heading2
和 heading4
将为了分别为6,2,1,1次服完(以重量计)。
Now I want to serve each heading based on their weightages. For instance, for first 10 requests/iterations, heading1
, heading3
, heading2
and heading4
would be served 6, 2, 1, and 1 times respectively in order (by weight).
有关服务的标题每次迭代show_count将由一个递增并total_views也将在全球范围增加。
For every iteration show_count of served heading will increment by one and total_views will also increment globally.
能否请您提出的算法或者一些红宝石code来处理这个问题。
Could you please suggest an algorithm or some ruby code to handle this.
推荐答案
这要根据你所需要的细节为您的基本情况,并可以修改:
This should work for your basic case and can be modified according to the details of what you need:
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}"
这篇关于重量随机项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!