In Java, given n Items, each with weight w, how does one choose a random Item from the collection with a chance equal to w?
Assume each weight is a double from 0.0 to 1.0, and that the weights in the collection sum to 1. Item.getWeight() returns the Item’s weight.
2020 Update (interesting how this got 37 upvotes with a glaring bug in the 2011 version below):
Math.random()yields a number very close to1.0, and we are unlucky with floating point precision: random index -1 would be the result, which is obviously wrong.2011 version (for comparison left in):