I have an array that I want to permutate randomly. In Java, there is a method Collections.shuffle() that can shuffle the elements of a List randomly. It can be used on an array too:
String[] array = new String[]{"a", "b", "c"};
// Shuffle the array; works because the list returned by Arrays.asList() is backed by the array
Collections.shuffle(Arrays.asList(array));
I tried using this on a Scala array, but the Scala interpreter responds with a lengthy answer:
scala> val a = Array("a", "b", "c")
a: Array[java.lang.String] = Array(a, b, c)
scala> java.util.Collections.shuffle(java.util.Arrays.asList(a))
<console>:6: warning: I'm seeing an array passed into a Java vararg.
I assume that the elements of this array should be passed as individual arguments to the vararg.
Therefore I follow the array with a `: _*', to mark it as a vararg argument.
If that's not what you want, compile this file with option -Xno-varargs-conversion.
java.util.Collections.shuffle(java.util.Arrays.asList(a))
^
<console>:6: error: type mismatch;
found : Array[java.lang.String]
required: Seq[Array[java.lang.String]]
java.util.Collections.shuffle(java.util.Arrays.asList(a))
^
What exactly is happening here? I don't want to compile my code with a special flag (-Xno-varargs-conversion), if that is the solution at all, just because of this.
So, how do I use Java's Collections.shuffle() on a Scala array?
I wrote my own shuffle method in Scala in the meantime:
// Fisher-Yates shuffle, see: http://en.wikipedia.org/wiki/Fisher–Yates_shuffle
def shuffle[T](array: Array[T]): Array[T] = {
val rnd = new java.util.Random
for (n <- Iterator.range(array.length - 1, 0, -1)) {
val k = rnd.nextInt(n + 1)
val t = array(k); array(k) = array(n); array(n) = t
}
return array
}
It shuffles the array in place, and returns the array itself for convenience.