Skip to content

Instantly share code, notes, and snippets.

@jesperdj
Created March 26, 2011 09:46
Show Gist options
  • Save jesperdj/888168 to your computer and use it in GitHub Desktop.
Save jesperdj/888168 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle
// Randomly permutate an array - Fisher-Yates shuffle (see: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
// This method can also take a custom swap method, which is useful for example for Latin hypercube sampling
def shuffle[@specialized(Double) T](array: Array[T], swap: (T, T) => (T, T) = { (a: T, b: T) => (b, a) }): Array[T] = {
val random = new scala.util.Random
for (n <- array.length - 1 to 0 by -1) {
val k = random.nextInt(n + 1)
val (a, b) = swap(array(k), array(n)); array(k) = a; array(n) = b
}
array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment