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.

Required fields*

10
  • 1
    Good point about binary search Commented May 29, 2012 at 14:28
  • 1
    Nevermind's answer doesn't need extra space, so it's O(1), but adds runtime complexity by repeatedly generating random numbers and evaluating the weight function (which, depending on the underlying problem, could be costly). Commented May 29, 2012 at 15:05
  • 2
    What you claim to be "more readable version" of my code is actually not. Your code needs to know total sum of weights, and cumulative sums, in advance; mine doesn't. Commented May 29, 2012 at 17:58
  • 1
    @Benjamin Kloster My code only calls weight function once per element - you can't do any better than that. You're right about random numbers, though. Commented May 29, 2012 at 17:59
  • 1
    @Nevermind: You only call it once per call to the pick-function, so if the user calls it twice, the weight function is called again for each element. Of course you could cache it, but then you're not O(1) for space complexity anymore. Commented May 29, 2012 at 19:29