471,086 Members | 1,453 Online

# generate random w/ weighting

I need to randomly pick films from a list to automatically generate a
timetable. Each film has a priority and weighting that affects how often it
is picked. For example, say we have 3 films with the following priority and
weighting,

A 1 5%
B 2 10%
C 3 5%

B should be picked more often because of the higher weighting. If films
have equal weighting, we look at the priority. So in this example, A should
have a higher 'overall weighting' than B.

Considering these factors, what is the best way to do this? Thanks.

jobz
Jul 21 '05 #1
1 1355
jobz <jo**@xmail.com> wrote:
I need to randomly pick films from a list to automatically generate a
timetable. Each film has a priority and weighting that affects how often it
is picked. For example, say we have 3 films with the following priority and
weighting,

A 1 5%
B 2 10%
C 3 5%

B should be picked more often because of the higher weighting. If films
have equal weighting, we look at the priority. So in this example, A should
have a higher 'overall weighting' than B.

Considering these factors, what is the best way to do this? Thanks.

Well, the "percent" in the above is somewhat confusing given that they
don't add up to 100, however:

Create a list, and for each element, add the outcome and the boundary
value it's valid for, ie the previous boundary (beginning with 0) +
weight.

You'll end up with a boundary being the total of all the weights.
Generate a random number between 0 and total-1
(ie Random.NextInt(total)) then step through the list until you find
the first element which has a boundary higher than that randomly
generated number.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet