Random Enumerators and Shufflers

Numerics.NET contains a number of utility classes that simplify working with randomized data. There are classes for shuffling data in random order, and for enumerating the members of a collection in random order. These classes reside in the Extreme.Mathematics.Random namespace.

Shuffling lists

The Shuffler class lets you shuffle the contents of any class that implements the List<T> interface. This includes arrays, vectors and many other objects.

The class has only one static (Shared in Visual Basic) method, Shuffle, which is overloaded. The first overload takes two arguments: an List<T>, and a Random that is used to generate the random sequence. This can be an instance of the Random itself, or one of the random number generators from the Extreme.Mathematics.Random namespace. The second variant only takes the list to shuffle, and uses a default random number generator.

C#
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6 };
Shuffler.Shuffle(numbers, new MersenneTwister());
for (int i = 0; i < numbers.Length; i++)
    Console.WriteLine(numbers[i]);

These methods overwrite the contents of the list with the shuffled data.

Enumerating Sequences in Random Order

The RandomizedCollection<T> class is a generic wrapper for sequences that enumerates the elements of the sequence in random order. The following example enumerates the elements of an array in random order:

C#
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6 };
var randomized = new RandomizedCollection<int>(numbers);
foreach (int number in randomized)
    Console.WriteLine(number);

RandomizedCollection<T> works most efficiently with collections that implement the IList<T> interface, but can work with IEnumerable<T> sequences as well. In the latter case, all the values in the sequence are enumerated before the first random element is returned.