0

I am developing a banner ads system. Each banner will be stored in the db. Each banner will have a wight(int number). How can I transform that in percentage efficiently?

For ex:

banner_1 70 banner_2 90 banner_3 150

and I want to have banner 1 displayed 22% second 29% third 48%

Radu D
  • 3,505
  • 9
  • 42
  • 69

6 Answers6

3

If the weights are w[1], w[2], ..., w[n], then the percentage p[i] for the i'th banner ad be:

p[i] = w[i] / sum(w)

That is, the weight of the given ad, divided by the total sum of the weights. Your database system should be able to calculate that fairly easily.

If you have relatively few ads, and the ads get many more views than updates, it may be worth caching this p[i] for each ad, and then recalculating it whenever you add, remove or modify the weight of an ad.

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
2

This is called (surprise) "weighted random numbers". The top answer to this question should help you out.

Community
  • 1
  • 1
Thomas
  • 174,939
  • 50
  • 355
  • 478
1

Assuming your using a SQL database with the weights stored, you can return the total weight and use it for calcuations:

SELECT BannerId, BannerUrl, BannerWeight, SUM(BannerWeight) as TotalWeight FROM Banners;

Then use something like this to find a value:

public int GetRandomRow(Row[] rows)
{
    int TotalWeight = 3;
    int rnd = Random(rows[0].TotalWeight);
    for (int row=0; row < rows.Count; row++)
    {
        if (rnd < rows[row])
            return row;
    }
}
Greg Buehler
  • 3,897
  • 3
  • 32
  • 39
0
Banner1 = (70 / (70 + 90 + 150))  * 100 s
Banner2 = (90 / (70 + 90 + 150))  * 100 s
Banner3 = (150 / (70 + 90 + 150)) * 100 s

Yeah, it a simple weighted average logic.

Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
0

If you just need weight to percentage conversion, that's really easy: you need to sum all the weights and then for each weight you divide it by sum and multiply by 100. It's O(n).

Vlad H
  • 3,629
  • 1
  • 19
  • 13
0

Fist off, your percentages add up to 99, so I'm going to guess that you rounded off some decimals.

To find the percentage of banner x you must sum up all the weights (to find 100 percent), the solve this equation: float percent = weight_x / sum of weights

Rich
  • 1,082
  • 7
  • 11