Effective way to get random item in Scala?

What is an effective way to get a random item from a collection in Scala? There is a related question there, but, like one of the comments, β€œthe question does not ask for any need for efficiency.”

+4
source share
4 answers

A custom collection may not be available for a fixed time. Therefore, you need a special collection with the desired property. For example - Vector or Array . See Collection Performance Specifications for others.

+6
source

Use a collection using the size () and get () methods with constant time.

+1
source

If you need a random order of all elements of the collection, then Random.shuffle is what you need. (It is better to convert the original collection into an array to avoid direct and inverse conversion.)

+1
source
 util.Random.shuffle(List.range(1,100)) take 3 
+1
source

Source: https://habr.com/ru/post/1501081/


All Articles