Created
January 4, 2014 00:32
-
-
Save mikedugan/8249637 to your computer and use it in GitHub Desktop.
a simple C# implementation of the fisher-yates shuffle used to randomize array elements without bias
This file contains hidden or 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
public static void Shuffle<T>(T[] array) | |
{ | |
var random = _random; | |
for (int i = array.Length; i > 1; i--) | |
{ | |
// Pick random element to swap. | |
int j = random.Next(i); // 0 <= j <= i-1 | |
// Swap. | |
T tmp = array[j]; | |
array[j] = array[i - 1]; | |
array[i - 1] = tmp; | |
} | |
} |
I created a modified version TWIMC:
static readonly Random Generator = new Random();
private static IEnumerable<T> ShuffleInternal<T>(IEnumerable<T> sequence, int take)
{
var retArray = sequence.ToArray();
// go through array, starting at the last-index
for (var i = retArray.Length - 1; i > take; i--)
{
var swapIndex = Generator.Next(0, i); // get num between 0 and index
if (swapIndex == i) continue; // don't replace with itself
var temp = retArray[i]; // get item at index i...
retArray[i] = retArray[swapIndex]; // set index i to new item
retArray[swapIndex] = temp; // place temp-item to swap-slot
}
return retArray;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code doesn't really work - it start with
var random = _random
which already fails, as_random
doesn't exist.I think it should be