Samstag, 20. Februar 2010

How to randomly shuffle a Sequence or List in Scala



val names = List("1","2","3","4","5")

List.fill(names.size)(scala.util.Random.nextInt).zipWithIndex.sortBy(identity).map(_._2).map(names(_))




or


val names = List("1","2","3","4","5","6","7")

Sorting.stableSort(names, (a:String, b:String) => Random.nextInt(2) == 1)
res11: Array[java.lang.String] = Array(2, 7, 4, 5, 1, 6, 3)

Keine Kommentare:

Kommentar veröffentlichen