The problem:
I have items that have weights. The higher the weight, the greater chance they have the item will go first. I need to have a clean, simple way of doing this that is based on core Java (no third party libraries, jars, etc.).
I've done this for 2 items, by summing the weights then randomly pick a number using Math.random()
within that range. Very simple. But for items greater than 2, I can either do more samples in the same range chancing misses, or I can recompute the sum of the weights of the remaining items and select again (recursive approach). I think that there might be something out there can can do this faster/cleaner. This code will be used over and over, so I'm looking for an effective solution.
In essence, its like randomized weight permutations.
Some Examples:
A
has weight of 1,B
has weight of 99. If I ran the simulation with this, I would expect to getBA
99% of the time andAB
1% of the time.A
has the weight of 10,B
has the weight of 10, andC
has the weight of 80. If I ran simulations with this, I would expectC
to be the first item in the ordering 80% of the time, in those cases,A
andB
would have an equal chance of being the next character.
Extra Details:
For my particular problem, there is a small number of items with potentially large weights. Say 20 to 50 items with weights that are stored in the form of a long, where the minimum weight is at least a 1000. The number of items may increase quite a bit too, so if we can find a solution that doesn't require the items to be small, that would be preferred.