SimpleGenerator.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. namespace TBL.CSharp.Utilities.Random.Generator
  3. {
  4. /// <summary>
  5. /// 简易随机数生成器
  6. /// <para>用于生成低质量的随机数;表现在不同设备上可以做到统一</para>
  7. /// </summary>
  8. public class SimpleGenerator : IRandom<SimpleGenerator.Seed>
  9. {
  10. /// <summary>
  11. /// 种子值
  12. /// </summary>
  13. private int _seed;
  14. /// <summary>
  15. /// 从种子构造
  16. /// </summary>
  17. /// <param name="seed">种子值</param>
  18. public SimpleGenerator(int seed) => RestoreBySeed(new Seed(seed));
  19. public int NextRaw()
  20. {
  21. _seed++;
  22. var a = _seed * 15485863;
  23. return a * a * a % 2038074743;
  24. }
  25. /// <summary>
  26. /// 获取一个 <c>0.0</c> ~ <c>1.0</c> 之间的随机数
  27. /// </summary>
  28. public double NextDouble()
  29. {
  30. _seed++;
  31. var a = _seed * 15485863;
  32. return Math.Abs((a * a * a % 2038074743) / 2038074743.0f);
  33. }
  34. public Seed DumpSeed() => new Seed(_seed);
  35. public void RestoreBySeed(Seed seed) => _seed = seed.SeedValue;
  36. /// <summary>
  37. /// 种子
  38. /// </summary>
  39. public readonly struct Seed
  40. {
  41. /// <summary>
  42. /// 种子值
  43. /// </summary>
  44. public readonly int SeedValue;
  45. /// <summary>
  46. /// 构造
  47. /// </summary>
  48. public Seed(int seed)
  49. {
  50. SeedValue = seed;
  51. }
  52. }
  53. }
  54. }