5

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".

Community
  • 1
  • 1
Dominykas Mostauskis
  • 7,797
  • 3
  • 48
  • 67
  • 1
    In case `size` method is efficient you should use `apple(randomIndexLessThanSize)`. In general there is no such method: for instance you can't get fair random element from infinite collection. – senia Sep 07 '13 at 15:59

4 Answers4

6

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.

Arseniy Zhizhelev
  • 2,381
  • 17
  • 21
2
util.Random.shuffle(List.range(1,100)) take 3 
René Höhle
  • 26,716
  • 22
  • 73
  • 82
haha1903
  • 76
  • 2
1

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

Garrett Hall
  • 29,524
  • 10
  • 61
  • 76
1

If you need random order of all collection elements, then Random.shuffle is what you need. (You'd better convert the original collection to array to avoid forward and backward conversion.)

Arseniy Zhizhelev
  • 2,381
  • 17
  • 21