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.
Not converting the
Set
to an ordered collection but usingzipWithIndex
we can attribute an index to each item in the collection,Thus for
val rnd = util.Random.nextInt(fruits.size)
,Given an empty set,
Solution1
Random way (
import scala.util.Random
)Solution2
Math way (no imports)
convert into
Vector
and get random element from itYou can directly access an element of a Set with slice. I used this when I was working with a set that was changing in size, so converting it to a Vector every time seemed like overkill.
If you don't mind an
O(n)
solution: