服务器页面基于权重

时间:2011-02-17 15:45:34

标签: ruby algorithm

假设我们有以下页面及其服务权重:

Page1    50%
Page2    20%
Page3    15%
Page4    15%

根据重量来提供页面的简单公式是什么?我正在使用Ruby。

这就是我的想法。

actual_pct = Weightage 
tot_hits = Total hits against the URL
served_pct = Served percentage for each page based on tot_hits
served_to_actual_pct  = served_pct x 100 / actual_pct

上面会给我一系列带有served_to_actual_pct的网页。让我们假设当没有提供任何页面或者多个页面具有相同的create timestamp时,我会根据他们的served_to_actual_pct提供这些页面。

根据这个假设,我可以在create timestamp上然后在served_to_actual_pct上对此数组进行排序。此时,数组中的第一页将是要提供的页面。

2 个答案:

答案 0 :(得分:2)

您需要的是加权样本:

class Hash
  def weighted_sample
    target = rand * self.values.reduce(:+)
    key, weight = self.detect{ |key, weight| target -= weight; target < 0 }
    return key
  end
end

添加任意数量的页面作为哈希的键,其权重为值。然后拨打your_hash.weighted_sample。价值较高的键会更频繁出现。

答案 1 :(得分:1)

在你的控制器中使用这样的东西

random = rand
if random < 0.5
  render 'view_1'
elsif random < 0.7
  render 'view_2'
elsif random < 0.85
  render 'view_3'
else
  render 'view_4'
end

rand返回0到1之间的随机浮点数。使用的if / else分支确保四个页面视图的概率为50%,20%,15%和15%。