Scala ListBuffer (or equivalent) shuffle

≡放荡痞女 提交于 2019-12-18 18:50:50

问题


Is there a simple shuffle function for Scala lists?

If not, whats the simplest way to implement?

I have a lot of these things to do all over the code, so the simpler the call, the best it is

An example in Ruby

a = [ 1, 2, 3 ]           #=> [1, 2, 3]
a.shuffle                 #=> [2, 3, 1] returns new array shuffled

Thanks in advance :)


回答1:


In Scala you can use scala.util.Random:

util.Random.shuffle((1 to 10).toSeq)
//Vector(9, 6, 8, 7, 10, 1, 2, 5, 3, 4)

util.Random.shuffle(List('A', 'B', 'C', 'D', 'E', 'F'))
//List(B, D, A, E, C, F)

Your results may vary...



来源:https://stackoverflow.com/questions/11040399/scala-listbuffer-or-equivalent-shuffle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!