Efficient way to get a random element in Scala?

2019-06-20 18:03发布

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

标签: scala random
4条回答
放我归山
2楼-- · 2019-06-20 18:32

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

查看更多
贪生不怕死
3楼-- · 2019-06-20 18:37

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

查看更多
Melony?
4楼-- · 2019-06-20 18:41

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.

查看更多
We Are One
5楼-- · 2019-06-20 18:50
util.Random.shuffle(List.range(1,100)) take 3 
查看更多
登录 后发表回答