Created
February 26, 2015 09:42
-
-
Save ozzieperez/a5efea1e7df7676780fc to your computer and use it in GitHub Desktop.
Randomly shuffles items in a list
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 ListShuffle | |
{ | |
public static void Shuffle<T>(this IList<T> list) | |
{ | |
Random rng = new Random(); | |
int n = list.Count; | |
while (n > 1) | |
{ | |
n--; | |
int k = rng.Next(n + 1); | |
T value = list[k]; | |
list[k] = list[n]; | |
list[n] = value; | |
} | |
} | |
public static void ShuffleHard<T>(this IList<T> list) | |
{ | |
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); | |
int n = list.Count; | |
while (n > 1) | |
{ | |
byte[] box = new byte[1]; | |
do provider.GetBytes(box); | |
while (!(box[0] < n * (Byte.MaxValue / n))); | |
int k = (box[0] % n); | |
n--; | |
T value = list[k]; | |
list[k] = list[n]; | |
list[n] = value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment