Why are there so many banner ads everywhere?

banner ads algorithm

  • 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%

  • Answer:

    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; } }

Radu D at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

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

This is called (surprise) "weighted random numbers". The top answer to http://stackoverflow.com/questions/1761626/weighted-random-numbers should help you out.

Thomas

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 http://en.wikipedia.org/wiki/Weighted_mean logic.

Senthil Kumaran

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

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

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.