Skip to content

Instantly share code, notes, and snippets.

@ozzieperez
Created February 26, 2015 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzieperez/a5efea1e7df7676780fc to your computer and use it in GitHub Desktop.
Save ozzieperez/a5efea1e7df7676780fc to your computer and use it in GitHub Desktop.
Randomly shuffles items in a list
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