Skip to content

Instantly share code, notes, and snippets.

@mikedugan
Created January 4, 2014 00:32
Show Gist options
  • Save mikedugan/8249637 to your computer and use it in GitHub Desktop.
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
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;
}
}
@iJungleboy
Copy link

iJungleboy commented Jan 30, 2017

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

var random = new Random();

@iJungleboy
Copy link

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