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

1
  • 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. Commented Sep 7, 2013 at 15:59

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.