Java – get random elements from a sequence collection

I talked about an API and gave me a Java util. A collection of iterators This means I can iterate over it, but I can't access these elements directly / randomly

Now my question: I want to get a random element from this set What do I do? I think I can create a new collection that allows direct access, but isn't it a little memory consumption? I can also traverse the entire collection and "roll a die" for each element to see if I should take the element and exit the iteration or continue However, I can't get the size of the set I need from the iterator

Thank you in advance

Solution

There is a method that can be executed through the collection at one time without using a lot of extra memory (just the size of an element in the collection plus a float) Pseudo code:

By collecting iterations. > Generate random floating point numbers for each project. > If the float is the lowest (or highest, it doesn't matter) seen so far, store the current item in the collection in a temporary variable (the new lowest random value is also stored.) > Once you reach the end of the set, you have a random item in the temp variable

Obviously, every time you call it, you will traverse the whole collection, but you don't have much choice

Update: the name of this type of problem finally came back to me This is called reservoir sampling

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>