From cf59c4158269cfc833bcab53fe106c672bc11f8e Mon Sep 17 00:00:00 2001 From: Paul Phillips Date: Thu, 28 May 2009 15:51:07 +0000 Subject: Added a sequence shuffling method to scala.util... Added a sequence shuffling method to scala.util.Random. --- src/library/scala/util/Random.scala | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'src/library') 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 Random 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 + } +} -- cgit v1.2.3