Created
March 26, 2011 09:46
-
-
Save jesperdj/888168 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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