summaryrefslogtreecommitdiff
path: root/src/library/scala/util/Random.scala
diff options
context:
space:
mode:
authorPaul Phillips <paulp@improving.org>2009-05-28 15:51:07 +0000
committerPaul Phillips <paulp@improving.org>2009-05-28 15:51:07 +0000
commitcf59c4158269cfc833bcab53fe106c672bc11f8e (patch)
treebd2c9582e8ed379c6358197858fde3794e68af55 /src/library/scala/util/Random.scala
parent8434c271e5fb1f6130aaf87a209aa84605dd7919 (diff)
downloadscala-cf59c4158269cfc833bcab53fe106c672bc11f8e.tar.gz
scala-cf59c4158269cfc833bcab53fe106c672bc11f8e.tar.bz2
scala-cf59c4158269cfc833bcab53fe106c672bc11f8e.zip
Added a sequence shuffling method to scala.util...
Added a sequence shuffling method to scala.util.Random.
Diffstat (limited to 'src/library/scala/util/Random.scala')
-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
+ }
+}