4

Assume I have a list of items each with a weight and I want to pick a random item. The easiest way to implement this is to keep the list of items and a running sum of the weights sorted by the sum. Then pick a random int from the max weight and do a binary search to find the item matching the random value. Not hard to do.

The question is there a more optimal way to choose the item than a binary search?

In my case I have 50,000 items and the weights are in a similar magnitude (ints) which precludes simply duplicating the items by weight times which makes picking one a simple array reference.

I don't need to know how to do this I simply wonder if there is a faster algorithm? I may want to do a lot of these so speed may be useful but memory isn't unlimited.

I'm using C++ in this case but doesn't have to be in any specific language.

ahwulf
  • 2,584
  • 15
  • 29
  • Note that though this is clearly not a duplicate of the one pointed to, your answer is there: not the accepted answer, which is the obvious one you point out, but jonderry's, which didn't get many votes. It seems pretty common around here for simpler answers to get more votes than correct ones. – Lee Daniel Crocker Jul 09 '13 at 02:21

0 Answers0