Possible Duplicate:
Generating random results by weight in PHP?
I have a web application where users can add 1-20 strings of text and assign a weight to them of how often it should show up. The system would then choose a random string based on the defined weights. What is the best way to go about this? Do the range values for the weight for each string matter? Could I just have the user assign a number (0-100) for each string? How would you go about choosing a random string? (Each choice doesn't worry about what was chosen before, every string has the same odds (based on weight) of being chosen at the start of each call).
I use this function in several PHP game engines:
Usage
Suppose I have the user weights in an associative array where each string points to its weight:
If I wanted to pull a string based on weight, I'd do this:
Here is a simple implementation:
With this function you can specify how many unique weighted random elements you want (IDEOne).
Nice answer is provided here, but there is a way to save on loockup loop. Faster way to select random value from array. Actually Idea is the same, just works faster as a simple loop.