Fisher–Yates Shuffle

Fisher–Yates shuffle, also known as Knuth shuffle, is an algorithm for generating a random permutation of a finite set—in plain terms, the algorithm shuffles the set. The algorithm effectively puts all the elements into a hat; it continually determines the next element by randomly drawing an element from the hat until no elements remain.



									Public Shared Function FisherYatesShuffle(data As Integer()) As Integer()
	Dim retVal As Integer() = New Integer(data.Length - 1) {}
	Dim ind As Integer() = New Integer(data.Length - 1) {}
	Dim index As Integer
	Dim rand As New Random()

	For i As Integer = 0 To data.Length - 1
		ind(i) = 0
	Next

	For i As Integer = 0 To data.Length - 1
		Do
			index = rand.[Next](data.Length)
		Loop While ind(index) <> 0

		ind(index) = 1
		retVal(i) = data(index)
	Next

	Return retVal
End Function
								


Example

									Dim data As Integer() = {486, 87, 522, 111, 894, 371, 1, 39}
Dim retVal As Integer() = FisherYatesShuffle(data)
								


Output

									retVal: { 39, 1, 111, 522, 486, 894, 371, 87 }