Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use Java Collections.shuffle() on a Scala array?
    primarykey
    data
    text
    <p>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:</p> <pre><code>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)); </code></pre> <p>I tried using this on a Scala array, but the Scala interpreter responds with a lengthy answer:</p> <pre><code>scala&gt; val a = Array("a", "b", "c") a: Array[java.lang.String] = Array(a, b, c) scala&gt; java.util.Collections.shuffle(java.util.Arrays.asList(a)) &lt;console&gt;: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)) ^ &lt;console&gt;:6: error: type mismatch; found : Array[java.lang.String] required: Seq[Array[java.lang.String]] java.util.Collections.shuffle(java.util.Arrays.asList(a)) ^ </code></pre> <p>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.</p> <p>So, how do I use Java's Collections.shuffle() on a Scala array?</p> <p>I wrote my own shuffle method in Scala in the meantime:</p> <pre><code>// 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 &lt;- 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 } </code></pre> <p>It shuffles the array in place, and returns the array itself for convenience.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload