summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/library/scala/util/Random.scala31
1 files changed, 30 insertions, 1 deletions
diff --git a/src/library/scala/util/Random.scala b/src/library/scala/util/Random.scala
index 09d15ff500..0bdf590df7 100644
--- a/src/library/scala/util/Random.scala
+++ b/src/library/scala/util/Random.scala
@@ -72,8 +72,37 @@ class Random(val self: java.util.Random) {
}
/** The object <code>Random</code> offers a default implementation
- * of scala.util.Random.
+ * of scala.util.Random and random-related convenience methods.
*
* @since 2.8
*/
object Random extends Random
+{
+ import collection.Sequence
+
+ /** Returns a new sequence in random order.
+ * @param seq the sequence to shuffle
+ * @return the shuffled sequence
+ */
+ def shuffle[T](seq: Sequence[T]): Sequence[T] = {
+ // It would be better if this preserved the shape of its container, but I have
+ // again been defeated by the lack of higher-kinded type inference. I can
+ // only make it work that way if it's called like
+ // shuffle[Int,List](List.range(0,100))
+ // which nicely defeats the "convenience" portion of "convenience method".
+ val buf: Array[T] = seq.toArray
+
+ def swap(i1: Int, i2: Int) {
+ val tmp = buf(i1)
+ buf(i1) = buf(i2)
+ buf(i2) = tmp
+ }
+
+ for (n <- buf.length to 2 by -1) {
+ val k = nextInt(n)
+ swap(n - 1, k)
+ }
+
+ buf.toSeq
+ }
+}