NRandom

repository·main·Indexed 42 days ago

https://github.com/nuskey8/nrandom

A high-performance pseudorandom number generation library for .NET and Unity. It features a unified IRandom abstraction layer with implementations like Xoshiro and PCG, LINQ extensions for random sequences, and weighted random selection via WeightedList<T>. Version 2.0.2 includes specialized support for System.Numerics and UnityEngine types (Vector2, Vector3, Quaternion, Color) through NRandom.Numerics and NRandom.Unity packages.

Tokens
5.9K
Snippets
21
Records
23
Agent score
44%

What's inside NRandom

  1. Handle weighted random selections

    main

    The NRandom.Collections namespace provides tools for weighted random selection via IWeightedCollection<T> and WeightedList<T>.

    Core Types:

    • IWeightedCollection<T>: An interface for collections holding weighted elements.
    • WeightedValue<T>: A struct representing a value and its associated double weight.
    • WeightedList<T>: A concrete implementation for managing weighted elements.

    Operations:

    • Add(T value, double weight): Adds an element with a specific weight.
    • GetRandom(): Retrieves a weighted random element.
    • RemoveRandom(out T item): Performs a weighted random draw and removes the selected item from the list.
    using NRandom.Collections;
    
    // Create a weighted list
    var weightedList = new WeightedList<string>();
    
    // Add elements with specified weights
    weightedList.Add("Legendary", 0.5);
    weightedList.Add("Epic", 2.5);
    weightedList.Add("Rare", 12);
    weightedList.Add("Uncommon", 25);
    weightedList.Add("Common", 60);
    
    // Retrieve a weighted random element
    var rarity = weightedList.GetRandom();
    
    // Draw without duplicates
    weightedList.RemoveRandom(out var item0);
  2. Implement the IRandom interface

    main

    The IRandom interface is the core abstraction for random number generation in NRandom. You can implement this interface to create custom generators.

    public interface IRandom
    {
        void InitState(uint seed);
        uint NextUInt();
        ulong NextULong();
    }

    NRandom provides several built-in implementations using various algorithms:

    Class NameAlgorithm
    ChaChaRandomChaCha (default: ChaCha8)
    MersenneTwisterRandomMersenne Twister (MT19937)
    Pcg32RandomPCG32 (PCG-XSH-RR)
    Philox4x32RandomPhilox4x32 (default: Philox4x32-10)
    Sfc32RandomSFC32
    Sfc64RandomSFC64
    SplitMix32Randomsplitmix32
    SplitMix64Randomsplitmix64
    TinyMt32RandomTiny Mersenne Twister (32bit)
    TinyMt64RandomTiny Mersenne Twister (64bit)
    Xorshift32Randomxorshift32
    Xorshift64Randomxorshift64
    Xorshift128Randomxorshift128
    Xoshiro128StarStarRandomxoshiro128**
    Xoshiro256StarStarRandomxoshiro256**
  3. Replace `rand.GetItem()` with `RandomElement()`

    main

    The GetItem() method used to retrieve a single random element has been removed in v2. Instead, use the RandomElement() extension method provided by the NRandom.Linq namespace.

    IRandom rand;
    T[] array;
    
    // RandomExtensions(v1)
    T result = rand.GetItem(array);
    
    // NRandom(v2)
    T result = array.RandomElement();
  4. Use NRandom.Numerics for System.Numerics types

    main

    By installing the NRandom.Numerics package, you can extend IRandom with methods for System.Numerics types like Vector2, Vector3, Vector4, and Quaternion.

    Installation

    .NET CLI

    dotnet add package NRandom.Numerics

    Package Manager

    Install-Package NRandom.Numerics

    Supported Types and Methods

    • Vector2: NextVector2(), NextVector2(max), NextVector2(min, max), NextVector2Direction(), NextVector2InsideCircle().
    • Vector3: NextVector3(), NextVector3(max), NextVector3(min, max), NextVector3Direction(), NextVector3InsideSphere().
    • Vector4: NextVector4(), NextVector4(max), NextVector4(min, max).
    • Quaternion: NextQuaternionRotation().
    using System.Numerics;
    using NRandom;
    using NRandom.Numerics;
    
    var rand = RandomEx.Create();
    
    // Vector2 examples
    rand.NextVector2();
    rand.NextVector2(new Vector2(10f, 10f));
    rand.NextVector2(new Vector2(10f, 10f), new Vector2(20f, 20f));
    rand.NextVector2Direction();    // Random direction vector (length 1)
    rand.NextVector2InsideCircle(); // Random coordinate inside a circle of radius 1
    
    // Vector3 examples
    rand.NextVector3();
    rand.NextVector3(new Vector3(10f, 10f, 10f));
    rand.NextVector3(new Vector3(10f, 10f, 10f), new Vector3(20f, 20f, 20f));
    rand.NextVector3Direction();    // Random direction vector (length 1)
    rand.NextVector3InsideSphere(); // Random coordinate inside a sphere of radius 1
    
    // Quaternion
    rand.NextQuaternionRotation();  // Random rotation
  5. Migrate from RandomExtensions (v1) to NRandom (v2)

    main

    When upgrading from RandomExtensions (v1) to NRandom (v2), you must update your namespaces and account for several breaking API changes. Specifically, the namespace has changed, certain extension methods have been moved to LINQ, and weighted collection methods have been renamed.

    Namespace Update

    Change your using directive from RandomExtensions to NRandom.

    Method Replacements

    • Random Element Selection: The GetItem() method has been removed. Use RandomElement() from the NRandom.Linq namespace instead.
    • Weighted Collections: For types implementing IWeightedCollection<T>, the methods GetItem() and GetItems() have been renamed to GetRandom() and GetRandom(Span<T> buffer) respectively.
    // v1 Namespace
    using RandomExtensions;
    
    // v2 Namespace
    using NRandom;
    // and for LINQ extensions
    using NRandom.Linq;
  6. Basic Usage of NRandom

    main

    You can use the thread-safe RandomEx.Shared instance for quick random generation, or create a new IRandom instance using RandomEx.Create() for seeded or non-thread-safe scenarios.

    Warning: RandomEx.Shared is thread-safe, but instances created via RandomEx.Create() or other IRandom implementations are not thread-safe.

    Note: Do not use this library for security purposes. Use System.Security.Cryptography.RandomNumberGenerator for cryptographically secure needs.

    using NRandom;
    
    // Get a random value between 0-9 using the shared instance
    var n = RandomEx.Shared.NextInt(0, 10);
    
    // Get a random boolean value
    var flag = RandomEx.Shared.NextBool();
    
    // Create a new instance (not thread-safe)
    var rand = RandomEx.Create();
    var d = rand.NextDouble(); // [0.0, 1.0)
  7. Install NRandom via NuGet or .NET CLI

    main

    NRandom requires .NET Standard 2.1 or higher. You can install it using the .NET CLI or the NuGet Package Manager.

    .NET CLI

    dotnet add package NRandom

    Package Manager

    Install-Package NRandom
    dotnet add package NRandom
  8. Install NRandom in Unity

    main

    To use NRandom in Unity, you need Unity 2021.3 or higher. The installation involves two steps: installing the core library via NuGet and then adding the Unity extension package via Git URL.

    1. Install Core Library:
      • Install NuGetForUnity.
      • Open NuGet > Manage NuGet Packages and search for/install the NRandom package.
    2. Install Unity Extension:
      • Open Window > Package Manager.
      • Click [+] > Add package from git URL.
      • Enter the following URL: https://github.com/nuskey8/NRandom.git?path=src/NRandom.Unity/Assets/NRandom.Unity
    https://github.com/nuskey8/NRandom.git?path=src/NRandom.Unity/Assets/NRandom.Unity
  9. Replace `IWeightedCollection<T>.GetItem()`/`GetItems()` with `GetRandom()`

    main

    For IWeightedCollection<T> implementations, the methods GetItem() and GetItems() have been renamed to GetRandom() in v2.

    WeightedList<T> list;
    Span<T> buffer;
    
    // RandomExtensions(v1)
    list.GetItem();
    list.GetItems(buffer);
    
    // NRandom(v2)
    list.GetRandom();
    list.GetRandom(buffer);
  10. Install NRandom via NuGet

    main

    NRandom requires .NET Standard 2.1 or higher. You can install it using the .NET CLI or the NuGet Package Manager.

    Using .NET CLI:

    dotnet add package NRandom

    Using Package Manager:

    Install-Package NRandom
    dotnet add package NRandom