diff --git a/Qrakhen.Randomize/Class1.cs b/Qrakhen.Randomize/Class1.cs deleted file mode 100644 index 86d74ee..0000000 --- a/Qrakhen.Randomize/Class1.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Qrakhen.Randomize -{ - public class Class1 - { - - } -} diff --git a/Qrakhen.Randomize/Dice.cs b/Qrakhen.Randomize/Dice.cs new file mode 100644 index 0000000..9dd51e6 --- /dev/null +++ b/Qrakhen.Randomize/Dice.cs @@ -0,0 +1,72 @@ +namespace Qrakhen.Randomize; + +public class Dice : IRandomizer +{ + public static uint MaxValue => uint.MaxValue; + + public static Dice? Global { get; private set; } + + private const uint P = 0x0100_0193; // prime + private const uint Q = 0x811C_9DC5; // basis + + private uint _n; + + public readonly uint Seed; + + public int Count { get; private set; } = 0; + + public Dice() : this((int)((DateTime.UtcNow.Ticks & 0xFFFF_FFFF) ^ Q)) { } + + public Dice(int seed) + { + Seed = (uint)seed; + _n = StrongHash(Q, Seed); + } + + //public float ExpRange(float from, float to, float q = .5f) + //{ + // q = Mathf.Clamp(q, 0, 1); + // float linear = Range(0f, 1f); + // float exponent = Mathf.Pow(2f, (0.5f - q) * 4f); + // float curvedRandom = Mathf.Pow(linear, exponent); + // return Mathf.Lerp(from, to, curvedRandom); + //} + + public uint Next() + { + unchecked + { + _n ^= Q; + _n *= P; + Count++; + + return (_n); + } + } + + public uint FastHash(uint v) + { + return (v ^ Q) * P; + } + + public uint StrongHash(uint v, uint q) + { + uint r = v; + r = (r ^ (q & 0xFF)) * P; + r = (r ^ ((q >> 0x08) & 0xFF)) * P; + r = (r ^ ((q >> 0x10) & 0xFF)) * P; + r = (r ^ ((q >> 0x18) & 0xFF)) * P; + + return r; + } + + public override string ToString() + { + return $"Dice "; + } + + public static void InitGlobal(int seed) + { + Global = new Dice(seed); + } +} \ No newline at end of file diff --git a/Qrakhen.Randomize/IRandomizer.cs b/Qrakhen.Randomize/IRandomizer.cs new file mode 100644 index 0000000..54d81b0 --- /dev/null +++ b/Qrakhen.Randomize/IRandomizer.cs @@ -0,0 +1,9 @@ +using System.Numerics; + +namespace Qrakhen.Randomize; + +public interface IRandomizer where T : INumber +{ + static abstract T MaxValue { get; } + T Next(); +} \ No newline at end of file diff --git a/Qrakhen.Randomize/RandomizerExtensions.cs b/Qrakhen.Randomize/RandomizerExtensions.cs new file mode 100644 index 0000000..5f01c8c --- /dev/null +++ b/Qrakhen.Randomize/RandomizerExtensions.cs @@ -0,0 +1,20 @@ +using System.Numerics; + +namespace Qrakhen.Randomize; + +public static class RandomizerExtensions +{ + public static TNumber Range(this TRandomizer randomizer, + TNumber fromInclusive, + TNumber toExclusive) + where TRandomizer : IRandomizer + where TRandomizerHash : INumber + where TNumber : INumber + { + return (TNumber)( + fromInclusive + + randomizer.Next() / ( + (dynamic)TRandomizer.MaxValue + 1.0) * + (fromInclusive - fromInclusive)); + } +} \ No newline at end of file