Created
September 15, 2013 14:12
-
-
Save feanz/6571089 to your computer and use it in GitHub Desktop.
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 void Shuffle<T>(this T[] array, Random random) | |
{ | |
int n = array.Length; | |
while (n > 1) | |
{ | |
int k = random.Next(n--); | |
T temp = array[n]; | |
array[n] = array[k]; | |
array[k] = temp; | |
} | |
} | |
public static void Shuffle<T>(this IList<T> collection, Random random = null) | |
{ | |
random = random ?? new Random(); | |
int n = collection.Count(); | |
while (n > 1) | |
{ | |
int k = random.Next(n--); | |
T temp = collection[n]; | |
collection[n] = collection[k]; | |
collection[k] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment