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:
add1 1 time
add2 5 times
add3 10 times
… and theoretically
addn 10 times

add1 1 time
add2 5 times
add3 10 times
… and theoretically
addn 10 times

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
“add1”
when 1…5
“add2”
when 6…15
“add3”
[…]
end

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:

ad_count = {“ad1” => 1, “ad2” => 5, “ad3” => 3}
N = ad_count.inject(0) {|total, (k,v)| total + v}
N.times do
key = ad_count.keys[rand(ad_count.size)]
puts key
ad_count[key] -= 1
ad_count.delete(key) if ad_count[key] <= 0
end

ad2
ad2
ad3
ad1
ad3
ad3
ad2
ad2
ad2

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

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.

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
badly

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}
ad1
ad3
ad3
ad2
ad2
ad2

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.

Jesus.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.