Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to get a random element in Scala?

Tags:

random

scala

What is an efficient way to get a random element from a collection in Scala? There's a related question here, but like one of the comments pointed out, "[that] question does not specify any efficiency needs".

like image 672
Dominykas Mostauskis Avatar asked Sep 07 '13 15:09

Dominykas Mostauskis


3 Answers

An arbitrary collection cannot be accessed in constant time. So you need some special collection with the desired property. For instance — Vector or Array. See Performance Characteristics of collections for others.

like image 155
Arseniy Zhizhelev Avatar answered Nov 02 '22 13:11

Arseniy Zhizhelev


util.Random.shuffle(List.range(1,100)) take 3 
like image 2
haha1903 Avatar answered Nov 02 '22 13:11

haha1903


Use a collection with a constant-time size() and get() method.

like image 1
Garrett Hall Avatar answered Nov 02 '22 12:11

Garrett Hall