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
  • Why do you shuffle it? If you inserted at the end and extracted random element (when you extract from the middle, you move the last element there to avoid shifting the array), it'd have O(1) insert , O(1) extraction and no need for reshuffle (I don't think the reshuffle as you defined it does anything useful) and the behaviour would be easier to understand. There would be equal probability for any element to be returned next, while the probabilities are probably skewed in some non-obvious way in the "grab-bag". Commented Jul 31, 2013 at 13:34
  • That's because there's two ways to use it - You can pop elements from the top one at a time, which doesn't require a reshuffle, or you can use an iterator to get a whole list without popping - in the latter case you must reshuffle or you'll get the same order every time. Commented Jul 31, 2013 at 14:53
  • But if it was an array and you just picked random element, you'd have to pop the elements if you wanted to get each element once (iterate whole array), but it would still not be any slower than the reshuffle. Commented Aug 1, 2013 at 7:06
  • True, performance-wise, there's no real difference, but if I just wanted a random ordering without depopulating the container, I'd have to pop everything, store it all in another location, and then reinsert them all again. The iterator method is merely a convenient way to avoid all that extra code. The one-at-a-time pop would probably be the more common usage though. Commented Aug 2, 2013 at 2:04
  • You wouldn't have to store it anywhere else. You would each time swap the selected element with the last and consider the array 1 shorter, so the used element would get beyond it. When done, you'd just mark the array the original size again as the order does not matter. Commented Aug 2, 2013 at 9:34