My Math 378 professor actually just touched on this algorithm the other day:
- Take the sum of all the relative weights and call it N
- Take a random number between 0 and 1, and multiply it by N. Call the new number X.
- Iterating through each element of the list do the following:
- Subtract the weight of the element from X.
- If X went negative, you are sitting on the chosen element, so quit.
- Otherwise, move to the next element.
Works nicely on both real and integer weights, and doesn't need extra storage to fill up a normalized array with duplicates. Also, the relative weights don't need to be normalized to probabilities.
blokhead