Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 7
    That first function is brilliant, but alas it doesn't weight the items correctly. Consider WeightedSelectionWithoutReplacement([(1, 'A'), (2, 'B')], 1). It will choose A with probability 1/4, not 1/3. Hard to fix. Commented Jan 28, 2010 at 14:27
  • Btw, faster but more complex algorithms are in my answer here: stackoverflow.com/questions/2140787/… Commented Jan 28, 2010 at 14:43
  • Nice find @JasonOrendorff. In fact the difference is quite bad. For weights (1, 2, 3, 4), you'd expect "1" to be chosen 1/10 of the time, but it'll be chosen 1/94 of the time. I really wanted that to work! Commented Mar 9, 2012 at 5:11
  • 1
    @JasonOrendorff: How did you calculate 1/4? If you have a formula for that, can we invert it and replace the original weights with weights that will give correct results? Commented Mar 9, 2012 at 6:44
  • @LawrenceKesteloot – for the 1/4, here's how I look at it: (random()*1) ranges from 0–1. If it's 1, the chance that it is larger than (random()*2) is 1/2. If it's 0, the chance is 0. The average chance is: 1/4. Commented Jan 18, 2017 at 20:12