# Algorithm for choosing object based on priority

Since I am not computer graduate (electro engineer as mater of fact) I
haven’t studied lots of computer algorithms. And since english is not my
first language I also find it difficult to search google.

What I would like to accomplish is create an algorithm for showing ads
based on priority (or number of times to display). Priority would define
no. of times ad would be displayed.

Example: We have 3 ads to display. If our web page is hit 16 times ads
should be displayed:
… and theoretically

Please direct me to a solution.

by
TheR

On Mon, Nov 26, 2012 at 3:23 PM, Damjan R. [email protected]
wrote:

… and theoretically

Please direct me to a solution.

I’m not sure I understand correctly, since 1 + 5 + 10 + … +
theoretically 10 is not 6, so I don’t really follow your example. If
you want to choose an ad among a set of ads each with a weigth, so
overall the number of times each ad is shown is proportional to the
weight:

r = rand(100) # 100 should be the sum of the weights, so 1 + 5 + 10 +
… + 10
case r
when 0
when 1…5
when 6…15
[…]
end

Hope this helps,

Jesus.

… and this sounds like a loaded die, as in

or

kaspar

Thanks so much. I guess I was over-complicating.

by
TheR

On Mon, Nov 26, 2012 at 6:10 PM, Damjan R. [email protected]
wrote:

Thanks so much. I guess I was over-complicating.

There could be one complication depending on the requirements. If you
have to guarantee that for every N ads you show there is exactly one
time ad1, 5 times ad2, etc summing up to N. Then the best way would be
to have a hash of counts, choose a random key and reduce the count,
removing the entry if the count is 0:

N = ad_count.inject(0) {|total, (k,v)| total + v}
N.times do
puts key
end

You could clone the hash and reassing it every time it’s empty or
something like that.

Jesus.

This algorithm has the consequence that the biggest weight entries
appear more at the end, since each key has the same probability of
being chosen. If you want weighted appearance, you should weigth the
random choosing with the counts.

Or to combine the two ideas, weight the die with the values from the
hash.

k

On Tue, Nov 27, 2012 at 8:00 AM, Kaspar S. [email protected] wrote:

This algorithm has the consequence that the biggest weight entries
appear more at the end, since each key has the same probability of
being chosen. If you want weighted appearance, you should weigth the
random choosing with the counts.

Or to combine the two ideas, weight the die with the values from the hash.

Yes, that’s what I meant, but rereading myself I explained it really

Jesus.

On Mon, Nov 26, 2012 at 6:30 PM, Jess Gabriel y Galn
[email protected] wrote:

N = ad_count.inject(0) {|total, (k,v)| total + v}