I talk to an API that gives me an java.util.Iterator
over a collection. That means I can iterate over it but I can't get direct/random access to the elements.
Now to my problem: I want to get one random element from this collection. How do i do that? I guess I could build a new collection that allows direct access, but isn't that a little memory consuming? I could also iterate over the entire collection and for each element "roll a dice" to see if I should take that element and quit iteration or continue. But then I need the size of the collection and I can't get that from the Iterator.
Thanks in advance.
In order to get random elements from the HashSet object, we need to generate a random number between 0 (inclusive) and the size of the HashSet (exclusive). And then iterate through the set till we reach the element located at the random number position as given below.
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
There's a way to do it on one pass through the collection that doesn't use a lot of extra memory (just the size of one element of the collection plus a float). In pseudocode:
Obviously this has the drawback of iterating through the entire collection every time you call it, but you don't have a lot of choice with the constraints you're facing.
Update: The name of this type of problem finally came back to me. This is called Reservoir sampling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With