For any given set, for instance,
val fruits = Set("apple", "grape", "pear", "banana")
how to get a random element from fruits
?
Many Thanks.
For any given set, for instance,
val fruits = Set("apple", "grape", "pear", "banana")
how to get a random element from fruits
?
Many Thanks.
Drawing inspiration from the other answers to this question, I've come up with:
This doesn't copy anything, doesn't fail if the
Set
(or other type ofTraversable
) is empty, and it's clear at a glance what it does. If you're certain that theSet
is not empty, you could use.head
instead ofheadOption
, returning aT
.So, every answer posted before has complexity O(n) in terms of space, since they create a copy a whole collection in some way. Here is a solution without any additional copying (therefore it is "constant space"):