Skip to content

Instantly share code, notes, and snippets.

@brenoferreira
Created November 4, 2013 18:19
Show Gist options
  • Save brenoferreira/7306949 to your computer and use it in GitHub Desktop.
Save brenoferreira/7306949 to your computer and use it in GitHub Desktop.
Shuffle IEnumerable extension method using Fisher–Yates shuffle algorithm (http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
public static class EnumerableEx
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> enumerable)
{
var array = enumerable.ToArray();
var random = new Random(DateTime.Now.Millisecond);
for (int i = array.Length - 1; i >= 1; i--)
{
var j = random.Next(0, i + 1);
Swap(array, i, j);
}
return array;
}
private static void Swap<T>(T[] array, int i, int j)
{
var aux = array[i];
array[i] = array[j];
array[j] = aux;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment