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:
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.
回答2:
util.Random.shuffle(List.range(1,100)) take 3
回答3:
Use a collection with a constant-time size() and get() method.
回答4:
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.)