chrisyarbrough / SharpShuffleBag

An efficient shuffle bag implementation in C# - for .NET and Unity projects.
MIT License
5 stars 1 forks source link

NuGet Version openupm

Sharp Shuffle Bag

An efficient and convenient shuffle bag implementation in C# for .NET and Unity projects.

Usage

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();
}

Motivation

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.

Support

Features