An efficient and convenient shuffle bag implementation in C# for .NET and Unity projects.
ShuffleBag<string> cradle = new() { "Whiskers", "Mia", "Dabbles" };
// Optionally, set a custom random source.
cradle.RandomSource = new SystemRandomSource(seed: 42);
// Retrieve 9 random cat names. Each cat is picked 3 times and no cat is picked twice in a row.
for (int i = 0; i < 9; i++)
{
string randomCat = cradle.Next();
}
Random number generators, as often used in games, have characteristics which can feel unnatural to humans. For example, a series of pseudo-random numbers like this:
[1, 2, 3, 4, 1, 1, 1, 1]
The shuffle bag algorithm attempts to make random feel more natural:
This will produce a non-repeating series like this:
[3, 4, 1, 2, 4, 3, 2, 1]
The Sharp Shuffle Bag implements this algorithm without causing unnecessary GC allocations and with consistent, fast performance. The randomization happens in-place while calling Next() and therefore avoids the larger performance spike of reshuffling/refilling the bag when it's empty.
ShuffleBag<T>
class to define a collection of items of type T.shuffleBag.Next()
to get the next random item from the bag. The bag will never empty.Next()
will never return the same item twice.shuffleBag.Next(markUsed: true)
for a fixed-size bag.RandomSource
for fine-grained control (e.g. to make the bag deterministic or set a seed).Shuffle.FisherYates(IList<T> list)
utility method to shuffle a list in-place.