Created
November 4, 2013 18:19
-
-
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)
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
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