Created
January 6, 2016 16:59
-
-
Save raducugheorghe/b90c4fd7ce571d1fb2e9 to your computer and use it in GitHub Desktop.
List shuffle (randomizer)
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 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