Skip to content

Instantly share code, notes, and snippets.

@raducugheorghe
Created January 6, 2016 16:59
Show Gist options
  • Save raducugheorghe/b90c4fd7ce571d1fb2e9 to your computer and use it in GitHub Desktop.
Save raducugheorghe/b90c4fd7ce571d1fb2e9 to your computer and use it in GitHub Desktop.
List shuffle (randomizer)
public static class ThreadSafeRandom
{
[ThreadStatic]
private static Random _local;
public static Random ThisThreadsRandom => _local ?? (_local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId)));
}
public static class ListShuffleExtension
{
public static void Shuffle<T>(this IList<T> list)
{
var n = list.Count;
while (n > 1)
{
n--;
var k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1);
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