dimanche 1 janvier 2017

Pick random key based on weight and picked times

I am designing an advertising system that rotates randomly between ads depending on their weight (bid).

local ads = local ads = {
    ["a"] = {
        views = 0,
        bid = 10
    },
    ["b"] = {
        views = 0,
        bid = 1000
    },
    ["c"] = {
        views = 0,
        bid = 100
    },
    ["d"] = {
        views = 0,
        bid = 50
    },
    ["e"] = {
        views = 0,
        bid = 500
    },
    ["f"] = {
        views = 0,
        bid = 10
    },
}

I searched around and found the following algorithm:

  1. Get sum of all weighted numbers
  2. Pick a random number between 0 and sum
  3. Loop through table (ads) and if (random number) <= weight then return ad else random number = random number - weight

Using the algorithm and looping 1,000 times prints out

a 3
c 60
b 581
e 313
d 35
f 8

which is pretty okay. But as you can see ad f has received almost 3 times as much views ad a, even with equal weight (bid).

I tried to make the algorithm more fair by also taking into account the views the ad already got. I did this by reducing the weight with each view.

I couldn't make it work though and I wonder if someone can help me?




Aucun commentaire:

Enregistrer un commentaire