Weight Based Server Page

Suppose we have the following pages and their portion weight:

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

What would be a simple formula for serving pages based on their weight? I am using Ruby.

This is how I think.

 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 

Above will provide me with an array of pages with their served_to_actual_pct . Suppose that I will serve pages based on their create timestamp when no pages are served yet or more than one page has the same served_to_actual_pct .

Based on this assumption, I can sort this array by create timestamp and then by served_to_actual_pct . At this point, the first page in the array will be the page that will be served.

0
source share
2 answers

You need a weighted sample:

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

Add as many pages as you want as hash keys with their weights as the value. Then call your_hash.weighted_sample . Keys with higher values ​​will appear more often.

+2
source

Use something like this in the controller

 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 returns a random floating-point number between 0 and 1. The used if / else fork provides 50%, 20%, 15%, and 15% probability for four page views.

+1
source

Source: https://habr.com/ru/post/1341820/


All Articles