KnownSeriesGenerator.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. namespace TBL.CSharp.Utilities.Random.Generator
  4. {
  5. /// <summary>
  6. /// 已知序列的随机数生成器
  7. /// <para>用于固定结果的演出教学等特殊用途</para>
  8. /// </summary>
  9. public class KnownSeriesGenerator : IRandom<KnownSeriesGenerator.Seed>
  10. {
  11. /// <summary>
  12. /// 已经生成的随机数计数
  13. /// </summary>
  14. private long _numberGenerated;
  15. /// <summary>
  16. /// 已知序列
  17. /// </summary>
  18. private readonly Queue<int> _series;
  19. /// <summary>
  20. /// 构造
  21. /// </summary>
  22. /// <param name="series">已知序列</param>
  23. /// <exception cref="ArgumentNullException">已知序列为空</exception>
  24. public KnownSeriesGenerator(params int[] series)
  25. {
  26. if (series == null)
  27. throw new ArgumentNullException(nameof(series));
  28. _series = new Queue<int>();
  29. foreach (var num in series)
  30. _series.Enqueue(num);
  31. }
  32. public int NextRaw()
  33. {
  34. var num = _series.Dequeue();
  35. _series.Enqueue(num);
  36. ++_numberGenerated;
  37. return num;
  38. }
  39. public Seed DumpSeed() => new Seed(_numberGenerated, _series);
  40. public void RestoreBySeed(Seed seed)
  41. {
  42. _series.Clear();
  43. foreach (var num in seed.KnownSeries)
  44. _series.Enqueue(num);
  45. _numberGenerated = seed.NumberGenerated;
  46. }
  47. /// <summary>
  48. /// 种子
  49. /// </summary>
  50. public readonly struct Seed
  51. {
  52. /// <summary>
  53. /// 已经生成的随机数计数
  54. /// </summary>
  55. public readonly long NumberGenerated;
  56. /// <summary>
  57. /// 已知序列
  58. /// </summary>
  59. public readonly int[] KnownSeries;
  60. /// <summary>
  61. /// 构造
  62. /// </summary>
  63. public Seed(long numberGenerated, Queue<int> knownSeries)
  64. {
  65. NumberGenerated = numberGenerated;
  66. KnownSeries = knownSeries.ToArray();
  67. }
  68. }
  69. }
  70. }