From f44eb67634a0bc511c25c5d71b4fb63b98740639 Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Sun, 30 Aug 2009 01:00:51 +0000 Subject: Some notes on the random shuffle implementation. --- src/library/scala/util/Random.scala | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/library/scala/util/Random.scala b/src/library/scala/util/Random.scala index 291b0d052a..ac01b9172c 100644 --- a/src/library/scala/util/Random.scala +++ b/src/library/scala/util/Random.scala @@ -113,13 +113,13 @@ object Random extends Random * @param seq the sequence to shuffle * @return the shuffled sequence */ - def shuffle[T](seq: Sequence[T]): Sequence[T] = { + def shuffle[T: ClassManifest](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 = seq.toVector + val buf = seq.toArray def swap(i1: Int, i2: Int) { val tmp = buf(i1) @@ -134,4 +134,27 @@ object Random extends Random buf.toSequence } + + /** I was consumed by weeping when I discovered how easy this + * is to implement in SequenceTemplate rather than trying to + * accomplish the inference from the outside. For reference + * here is the shape-preserving implementation. + */ + // def shuffle: This = { + // import scala.util.Random.nextInt + // val buf = thisCollection.toVector + // + // 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) + // } + // + // newBuilder ++= buf result + // } } -- cgit v1.2.3